Customed distance function Haversine

14 ビュー (過去 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 Center および File ExchangeStatistics 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