矢量化向量之间的距离计算 [英] Vectorizing distance calculation between vectors
问题描述
我给出了一个3×1000(及后来的3×10 000)矩阵 cord
,其中包含我的像素的三维坐标。
$ b
我的意图是计算所有像素之间的距离,我用一个for循环(见下面)来做,但是我将不得不很快计算这个庞大的矩阵,并且想知道是否我可以矢量化代码,使其更快...?
$ b $ $ p $ dist = zeros(size(cord,2),size(线,2));
for i = 1:size(cord,2)
for j = 1:size(cord,2)
dist(i,j)= norm(cord(:,i) - 帘线(:,J));
dist(j,i)= dist(i,j);
end
end
< a href =http://www.mathworks.es/es/help/stats/pdist.html =nofollow> pdist
确实如此那。 squareform
是需要以正方形对称矩阵的形式得到结果:
$ $ $ $ $ $ c $ dist dist = squareform(pdist(cord。')) ;
I have a 3 X 1000 (and later 3 X 10 000) matrix cord
given, which contains the three dimensional coordinates for my pixels.
My intention is to calculate the distance between all the pixels, and I do it with a for loop (see below), but I will have to calculate this for huge matrices soon, and am wondering if I could vectorize the code for making it faster...?
dist = zeros(size(cord,2),size(cord,2));
for i = 1:size(cord,2)
for j = 1:size(cord,2)
dist(i,j) = norm(cord(:,i)-cord(:,j));
dist(j,i) = dist(i,j);
end
end
pdist
does exactly that. squareform
is needed to get the result in the form of a square, symmetric matrix:
dist = squareform(pdist(cord.'));
这篇关于矢量化向量之间的距离计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!