【发布时间】:2013-10-14 12:15:19
【问题描述】:
我有很多点,我想建立距离矩阵,即每个点与所有其他点的距离,但我不想使用 from 循环,因为时间太长...... 构建这个矩阵有更好的方法吗? 这是我的循环:对于大小为 10000x3 的 setl,此方法需要花费我很多时间 :(
for i=1:size(setl,1)
for j=1:size(setl,1)
dist = sqrt((xl(i)-xl(j))^2+(yl(i)-yl(j))^2+...
(zl(i)-zl(j))^2);
distanceMatrix(i,j) = dist;
end
end
【问题讨论】:
-
你有统计工具箱吗?如果是,那么:mathworks.com/help/stats/pdist.html
-
您只需要计算矩阵的一半,因为两点之间的距离是对称的(例如 d(x,y)=d(y,x) )。否则会计算两次。
-
不,如果你使用
pdist,距离只计算一次。然后可以使用squareform来构建对称距离矩阵。见my answer here。您也可以输入edit squareform来查看使用的代码(没有for循环)。 -
如果你关心速度,
pdist(一个原生 C 函数)和squareform是唯一的选择,除非你想try compiling mex code 更快一点。
标签: matlab matrix vectorization distance linear-algebra