This is well done. I especially appreciate the multiple input methods.
The flag=0 method can easily return imaginary results for noisy data. Note that the flag=0 method is also trying to find the primary axes of the ellipsoid. For those getting imaginary results when using flat=0 (the default), if your ellipsoid is expected to already be aligned with x, y, and z, then just use flag=1. This works quite well even when flag=0 falls apart.
I see some folks are using this for magnetometer data, which has a "hard iron" offset. To convert from raw data to points on a unit sphere:
[c, r] = ellipsoid_fit(raw, 1);
% For a single point, k:
unit_sphere(:, k) = (raw(:, k) - c)./r
% For multiple points, vectorized:
unit_sphere = diag(1./r) * (m - c * ones(1, size(m, 2)));
% Just for kicks using bsxfun:
unit_sphere = bsxfun(@times, 1./r, bsxfun(@minus, m, c))
I used your code but the results are not correct with my data. The eigen values are very big. Should you normalise the Covariance matrix? I would also want to ask how did you derive from the 9 parameters of ellipsoid, the covariance matrix, center etc.. which book, notes did u use?