find the distance between two points on a globe given latitude and longtitude in matlab

To find the distance between two points on the globe, we can use the geodetic and geography functions in Matlab. The distance calculation can be based on the Haversine formula, which takes into account the curvature of the earth. Here's how to do it:

main.m
% Latitude and longitude of point A in degrees
latA = 42.3601; % Boston, MA
lonA = -71.0589;

% Latitude and longitude of point B in degrees
latB = 37.7749; % San Francisco, CA
lonB = -122.4194;

% Convert latitudes and longitudes to radians
latARad = deg2rad(latA);
lonARad = deg2rad(lonA);
latBRad = deg2rad(latB);
lonBRad = deg2rad(lonB);

% Compute distance using Haversine formula
r = 6371; % Earth's radius in km
dlat = latBRad - latARad;
dlon = lonBRad - lonARad;
a = sin(dlat/2)^2 + cos(latARad)*cos(latBRad)*sin(dlon/2)^2;
c = 2*atan2(sqrt(a), sqrt(1-a));
dist = r*c; % distance in km
594 chars
22 lines

The dist variable now contains the distance between the two points in kilometers. The Haversine formula is a good approximation for short distances, but for longer distances or greater accuracy, other formulas may be used.

gistlibby LogSnag