Customed distance function Haversine

16 views (last 30 days)
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 Comment
SALAH ALRABEEI
SALAH ALRABEEI on 21 Jun 2021
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);

Sign in to comment.

Accepted Answer

Scott MacKenzie
Scott MacKenzie on 21 Jun 2021
Edited: Scott MacKenzie on 26 Jun 2021
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
  2 Comments
Miguel Angel Sanchez Aportela
Thank you so much, it worked really well!
Scott MacKenzie
Scott MacKenzie on 13 Jul 2021
@Miguel Angel Sanchez Aportela You're welcome. Glad to help. Good luck with your research.

Sign in to comment.

More Answers (0)

Categories

Find more on Statistics and Machine Learning Toolbox in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!