Customed distance function Haversine

조회 수: 13 (최근 30일)
Miguel Angel Sanchez Aportela
Miguel Angel Sanchez Aportela 2021년 6월 9일
댓글: Scott MacKenzie 2021년 7월 13일
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
  댓글 수: 2
Miguel Angel Sanchez Aportela
Miguel Angel Sanchez Aportela 2021년 7월 13일
Thank you so much, it worked really well!
Scott MacKenzie
Scott MacKenzie 2021년 7월 13일
@Miguel Angel Sanchez Aportela You're welcome. Glad to help. Good luck with your research.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Statistics and Machine Learning Toolbox에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by