3D中每2个点之间的相互距离

时间:2011-06-05 12:45:57

标签: matlab

rv=[rx ry rz];   %# [N-by-3] rx , ry , rz are [N-by-1]

for i=1:N
    for j=1:N
        dx(i,j)=rv(i,1)-rv(j,1);    %# dx is x component of distance between each 2 points [N-by-N]
        dy(i,j)=rv(i,2)-rv(j,2);
        dz(i,j)=rv(i,3)-rv(j,3);
    end
end
d=cat(3,dx,dy,dz);

是否有更快的方法来构建 d

非常感谢任何指南。

编辑:

N= 997 
Me:               Elapsed time is 17.271125 seconds.
DiggyF:           Elapsed time is 0.241841 seconds.
Oli Charlesworth: Elapsed time is 0.120425 seconds.
N=1986 
DiggyF          : Elapsed time is 1.183639 seconds.
Oli Charlesworth: Elapsed time is 0.502964 seconds.

2 个答案:

答案 0 :(得分:2)

这是一种避免显式循环的方法:

dx = repmat(rx, 1, N) - repmat(rx.', N, 1);

我不知道这是否会更快;你必须尝试一下!

答案 1 :(得分:1)

这也有效:

dx = meshgrid(rx) - meshgrid(rx)'
dy = meshgrid(ry) - meshgrid(ry)'
dz = meshgrid(rz) - meshgrid(ry)'

如果您有统计工具箱或八度音,请查看pdist函数。