How to rewrite parfor loop using arrayfun to compute on GPU?
5 views (last 30 days)
Show older comments
Is there a way to rewrite this parfor/for loops to compute on GPU using arrayfun? And will there be any difference?
parfor i = 1:size(A,1)
for j = i+1:size(A,1)
for k = j+1:size(A,1)
sumMatrix = [sumMatrix; [(A(i) + A(j) + A(k)) A(i) A(j) A(k)]];
end
end
end
A is a vector of integers.
0 Comments
Answers (1)
Joss Knight
on 15 Feb 2016
Edited: Joss Knight
on 15 Feb 2016
Seems like you're just trying to add together all the elements of A in every permutation, with the proviso that k > j > i. So really you shouldn't be using loops at all. Just form the list of numbers you want to add and prune out all the ones you don't want.
[Ak, Aj, Ai] = ndgrid(A);
[maskK, maskJ, maskI] = ndgrid(1:numel(A));
mask = maskJ > maskI & maskK > maskJ;
Acat = [Ai(mask) Aj(mask) Ak(mask)];
sumMatrix2 = [sum(Acat,2) Acat];
In answer to your last question, yes, it makes an astronomical difference. With even 100 numbers the looping method takes several minutes while the vectorized method takes a fraction of a second. Although you could speed up the looping method a massive amount by preallocating the output.
1 Comment
See Also
Categories
Find more on GPU Computing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!