1

我的矩阵 datamat 具有 XY 坐标:

-80.26 40.11
-80.44 40.24
-80.29 40.49
-80.45 40.48
-80.55 40.90
-80.32 40.19

我必须计算所有对的距离,其数量为 6*5/2=15。距离只是 sqrt((x_i-x_j)^2+(y_i-y_j)^2)。如何创建一个存储这十五个距离值的向量?谢谢。

4

1 回答 1

1

这里有两种可能的解决方案。第一个使用单个循环,但在该结构中相当有效。第二种是无循环的,但需要分配额外的矩阵A。我在两者上都进行了一些定时运行(见下文),并且无循环解决方案表现最佳。

%# Your matrix
M = [-80.26 40.11;
     -80.44 40.24;
     -80.29 40.49;
     -80.45 40.48;
     -80.55 40.90;
     -80.32 40.19];

%# Get the indices of all combinations
I1 = combnk(1:size(M, 1), 2);
T = size(I1, 1);

%# Loop-based solution
Soln1 = nan(T, 1);
for n = 1:T
    Soln1(n) = sqrt((M(I1(n, 1), 1) - M(I1(n, 2), 1))^2 + (M(I1(n, 1), 2) - M(I1(n, 2), 2))^2);
end 

%# Loop-less but requires the creation of matrix A
A = M(I1', :);
A = A(2:2:end, :) - A(1:2:end, :);
Soln2 = sqrt(sum(A.^2, 2));

对于一个有 100 行的随机矩阵M,我对每个解决方案执行了 1000 次迭代。结果是:

Elapsed time is 0.440229 seconds. %# Loop based solution
Elapsed time is 0.168733 seconds. %# Loop-less solution

无循环解决方案似乎是赢家。

于 2013-01-30T23:47:27.090 回答