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 个评论

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');
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

0 个投票

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 个)

类别

在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by