How to parallel this code?

1 view (last 30 days)
tao jiang
tao jiang on 7 Oct 2016
Commented: Walter Roberson on 7 Oct 2016
function d = compute_d(vertex)
%vertex is nvert by 3 matrix;
nvert= max(size(vertex));
d = [];
for i = 1:nvert-1
for j = i+1:nvert
x_ij = vertex(i,:) - vertex(j,:);
d = [d; x_ij/norm(x_ij)];
end
end
save('d', 'd');
  2 Comments
tao jiang
tao jiang on 7 Oct 2016
I try to use the code below to parallel, but it said the variable isn't sliced. How should I do to deal with this problem? thx
function d = compute_d_pal(vertex)
%vertex = cat(2,vertex1(:,1),vertex1(:,2),zeros(size(vertex1,1),1));
nvert= max(size(vertex));
n = nvert*(nvert-1)/2;
d = zeros(nvert*(nvert-1)/2,3);
parfor i = 1:nvert-1
for j = i+1:nvert
x_ij = vertex(i,:) - vertex(j,:);
%d = [d; x_ij/norm(x_ij)];
index = nvert*(nvert-1)/2 - (nvert-i)*(nvert-i+1)/2 + j - i;
d( index,: ) = x_ij/norm(x_ij);
end
end
save('d', 'd');
Walter Roberson
Walter Roberson on 7 Oct 2016
The object your store into, d, cannot have an index that complicated. You should switch to a linear index that you then break up into i and j.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 7 Oct 2016
The biggest speed up would be to pre-allocate d. It will run (nvert) * (nvert+1) / 2 times, it appears, each size(vertex,2) rows, so you can figure out the needed memory ahead of time, and store into the right place in the matrix.
You can use a linear index instead of a double-nested loop, decoding the linear index into the proper i/j pair. And that allows you to use a something-by-3 output matrix with its first index being the linear index. If you had not sped the code up enough already by that point, you could parfor that linear index -- but I suspect that would end up slowing things down.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!