필터 지우기
필터 지우기

How to parallel this code?

조회 수: 2 (최근 30일)
tao jiang
tao jiang 2016년 10월 7일
댓글: Walter Roberson 2016년 10월 7일
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
tao jiang
tao jiang 2016년 10월 7일
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 2016년 10월 7일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2016년 10월 7일
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by