Customed distance function Haversine
16 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Miguel Angel Sanchez Aportela
el 9 de Jun. de 2021
Comentada: Scott MacKenzie
el 13 de Jul. de 2021
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 comentario
SALAH ALRABEEI
el 21 de Jun. de 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);
Respuesta aceptada
Scott MacKenzie
el 21 de Jun. de 2021
Editada: Scott MacKenzie
el 26 de Jun. de 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 comentarios
Scott MacKenzie
el 13 de Jul. de 2021
@Miguel Angel Sanchez Aportela You're welcome. Glad to help. Good luck with your research.
Más respuestas (0)
Ver también
Categorías
Más información sobre Statistics and Machine Learning Toolbox en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!