Customed distance function Haversine

13 次查看(过去 30 天)
For a proyect I want to use pdist2 (Pairwise distance between two sets of observations) but I need an specific function.
I have two data sets of different sizes, one of which is a nx2 matrix of latitude, longitude.
I'm trying to calculate Haversine distance but I don't know how to apply the funtion in this case. Would you help correcting my function? Thank you in advance.
axa = pdist2(latlon1(:, 1:2), latlon2(:, 1:2), @haversine);
function [dist] = haversine(lat1,lon1,lat2,lon2)
dist = 2 * 6372.8 * asin(sqrt(sind((lat2-lat1)/2)^2 + cosd(lat1) * cosd(lat2) * sind((lon2 - lon1)/2)^2));
end
  1 个评论
SALAH ALRABEEI
SALAH ALRABEEI 2021-6-21
pdist2 has only three metric distances ( 'seuclidean', 'minkowski', or 'mahalanobis').
So since your lon and lat are not of the same length; you can create grid
[x,y]=meshgrid(lon,lat);

请先登录,再进行评论。

采纳的回答

Scott MacKenzie
Scott MacKenzie 2021-6-21
编辑:Scott MacKenzie 2021-6-26
You need to re-work your haversine function, as per the requirements for distance functions used with pdist2. A custom distance function for pdist2 needs two input arguments and the first must specify just a single observation:
axa = pdist2(latlon1(1, 1:2), latlon2(:, 1:2), @haversine); % repeat for other values in latlon1
function [dist] = haversine(ZI, ZJ)
lat1 = ZI(1,1);
lon1 = ZI(1,2);
lat2 = ZJ(:,1);
lon2 = ZJ(:,2);
dist = 2 * 6372.8 * asin(sqrt(sind((lat2-lat1)/2)^2 + cosd(lat1) * cosd(lat2) * sind((lon2 - lon1)/2)^2));
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Statistics and Machine Learning Toolbox 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by