Clear Filters
Clear Filters

How to use GPU to define a large 3D matrix

3 views (last 30 days)
Dear all,
I am trying to use the attached M file (mkdelta.m) to difine a large 3d matrix (5598x40x40). It will cost large amount of CPU time to finish, which is unbearable. I am considering to use GPU to accelerate the computation. I have GPU in my computer but I have no idea how to use it to do this. Could you give me some tutorial?
Best regards.
Yeping Sun

Accepted Answer

James Tursa
James Tursa on 19 Sep 2016
Edited: James Tursa on 19 Sep 2016
For starters, put semi-colons at the end of the delta(etc) = etc lines so that intermediate stuff doesn't print to the screen. Doing just that cuts the execution time to under 1 sec on my computer. E.g.,
delta(k,i,j)=1; % <-- appended semi-colon
else delta(k,i,j)=0; <-- appended semi-colon
For more speed improvements, could work on vectorizing the loops. This should get you all the speed improvements needed without resorting to some type of GPU conversion. E.g., here is one way to vectorize the code with simple brute force application of the bsxfun function to each of your operations:
pc1_1 = pc1(:); % Convert to column vector in 1st dimension
pc2_1 = pc2(:); % Convert to column vector in 1st dimension
x1_2 = reshape(x1,1,40,1); % Convert to "vector" in 2nd dimension
x2_3 = reshape(x2,1,1,40); % Convert to "vector" in 3rd dimension
arg1 = bsxfun(@le,x1_2-c1,pc1_1);
arg2 = bsxfun(@lt,pc1_1,x1_2+c1);
arg3 = bsxfun(@le,x2_3-c2,pc2_1);
arg4 = bsxfun(@lt,pc2_1,x2_3+c2);
arg12 = bsxfun(@and,arg1,arg2);
arg34 = bsxfun(@and,arg3,arg4);
delta = bsxfun(@and,arg12,arg34);
delta(:,40,:) = bsxfun(@eq,pc1_1,x1_2+c1);
delta(:,:,40) = bsxfun(@eq,pc2_1,x2_3+c2);
There may be a way to simplify this even further, but the above code runs in about 0.02 sec on my machine so I stopped working on it.
  1 Comment
Yeping Sun
Yeping Sun on 20 Sep 2016
Edited: Yeping Sun on 20 Sep 2016
Thanks a lot. That's very helpful. But when I compare the two matrices produced by my original code and by your bsxfun code with "isequal", it returns "0", which means that the two matrices are different. I cannot work out why. Could you check it? I've attached my matlab workspace file PC1-PC2.mat with the comment.
Best regards.

Sign in to comment.

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!