Matlab中的经度,纬度和距离

时间:2013-01-30 23:25:58

标签: matlab for-loop coordinate

我的矩阵datamat具有X-Y坐标:

-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)。如何创建存储十五个距离值的矢量?感谢。

1 个答案:

答案 0 :(得分: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

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

相关问题