Skip to content

Instantly share code, notes, and snippets.

@adonese
Created May 1, 2016 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adonese/fdda87dd70d6d0ceac9e3ca136cf9dd9 to your computer and use it in GitHub Desktop.
Save adonese/fdda87dd70d6d0ceac9e3ca136cf9dd9 to your computer and use it in GitHub Desktop.
function [lat, lon, h] = xyz2ell(X, Y, Z, a, e2)
% XYZ2ELL Converts cartesian coordinates to ellipsoidal coodinates.
% We can add some default values here, i.e. a and e2.
% Latitude and height convergence criteria
eps_lat = 1.e-12;
eps_height = 1.e-5;
% Initial values...
p = sqrt(X .* X + Y .* Y);
lat = atan2(Z, p .* (1 - e2));
h = 0;
dh = 1;
dlat = 1;
% Iterate until convergence, the difference between lat(i) and lat(i - 1) <= eps, and so for the height.
while sum(dlat > eps_lat) | sum(dh > eps_height)
lat0 = lat;
h0 = h;
v = a ./ sqrt(1 - e2 .* sin(lat) .* sin(lat));
h = p ./ cos(lat) - v;
lat = atan2(Z, p .* (1 - e2 .* v ./ (v + h)));
dlat = abs(lat-lat0);
dh = abs(h - h0);
end
lon = atan2(Y, X);
% For reference for atan2() uses refer to cens.ioc.ee/local/matlab/techdoc/ref/atan2.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment