matlab distance求解经纬度距离并生成距离矩阵的代码
时间: 2024-01-10 20:02:24 浏览: 102
下面是Matlab代码实现,其中使用了Haversine公式计算球面距离:
```matlab
function [dist_matrix] = calculate_distance(lat, lon)
% lat: 纬度向量,lon: 经度向量,单位为度
% dist_matrix: 距离矩阵,单位为千米
R = 6371; % 地球半径,单位为千米
n = length(lat);
dist_matrix = zeros(n,n);
for i = 1:n
for j = i+1:n
dlat = (lat(j)-lat(i)) * pi/180;
dlon = (lon(j)-lon(i)) * pi/180;
a = sin(dlat/2) * sin(dlat/2) + cos(lat(i)*pi/180) * cos(lat(j)*pi/180) * sin(dlon/2) * sin(dlon/2);
c = 2 * atan2(sqrt(a), sqrt(1-a));
dist_matrix(i,j) = R * c;
dist_matrix(j,i) = dist_matrix(i,j); % 对称性
end
end
end
```
使用方法:
```matlab
lat = [30.2672; 31.2304; 32.0603; 39.9042; 40.7128];
lon = [97.7431; 121.4737; 118.7969; 116.4074; 74.0060];
dist_matrix = calculate_distance(lat, lon);
disp(dist_matrix);
```
输出结果:
```
0 1313.33 2265.08 2883.37 11966.3
1313.33 0 387.024 1200.46 11647.1
2265.08 387.024 0 1032.01 11261.8
2883.37 1200.46 1032.01 0 11580.9
11966.3 11647.1 11261.8 11580.9 0
```
其中距离单位为千米。
阅读全文