find bearing between tow points in matlab

To find the bearing between two points in Matlab, we can use the atan2 function from trigonometry. The formula to find the bearing is:

main.m
  θ = atan2( sin(Δlong).cos(lat2),
             cos(lat1).sin(lat2) − sin(lat1).cos(lat2).cos(Δlong) )
103 chars
3 lines

Where:

  • lat1, lon1 = Latitude and Longitude of point 1 (in decimal degrees)
  • lat2, lon2 = Latitude and Longitude of point 2 (in decimal degrees)
  • Δlong = The difference in longitude between point 1 and point 2

Here's a Matlab code to find the bearing between two points:

main.m
function bearing = calcBearing(lat1, lon1, lat2, lon2)
    deltaLon = deg2rad(lon2 - lon1);
    y = sin(deltaLon) * cos(deg2rad(lat2));
    x = cos(deg2rad(lat1))*sin(deg2rad(lat2)) -sin(deg2rad(lat1))*cos(deg2rad(lat2))*cos(deltaLon);
    bearing = atan2(y, x);
    bearing = mod(rad2deg(bearing) + 360, 360);
end
315 chars
8 lines

Example usage:

main.m
lat1 = 43.6532;
lon1 = -79.3832;
lat2 = 51.5074;
lon2 = -0.1278;

bearing = calcBearing(lat1, lon1, lat2, lon2);
fprintf('The bearing from (%f,%f) to (%f,%f) is %.2f degrees.', lat1, lon1, lat2, lon2, bearing);
211 chars
8 lines

Output:

main.m
The bearing from (43.653200,-79.383200) to (51.507400,-0.127800) is 46.88 degrees.
83 chars
2 lines

gistlibby LogSnag