function report=ellipsefit(XY)
X=XY(1,:).';
Y=XY(2,:).';
M= [X.^2, X.*Y, Y.^2, X, Y, -ones(size(X,1),1)];
[U,S,V]=svd(M,0);
ABCDEF=V(:,end);
if size(ABCDEF,2)>1
error 'Data cannot be fit with unique ellipse'
else
ABCDEF=num2cell(ABCDEF);
end
[A,B,C,D,E,F]=deal(ABCDEF{:});
Q=[A, B/2;B/2 C];
x0=-Q\[D;E]/2;
dd=F+x0'*Q*x0;
Q=Q/dd;
[R,eigen]=eig(Q);
eigen=eigen([1,4]);
if ~all(eigen>=0), error 'Fit produced a non-elliptic conic section'; end
idx=eigen>0;
eigen(idx)=1./eigen(idx);
AxesDiams = 2*sqrt(eigen);
theta=atand(tand(-atan2(R(1),R(2))*180/pi));
report.Q=Q;
report.d=x0(:).';
report.ABCDE=[A, B, C, D, E]/F;
report.AxesDiams=sort(AxesDiams(:)).';
report.theta=theta;
Best Answer