function [z, r] = circle (X, z, r);
%CIRCLE         Geometric circle fit
%
% [z,r] = circle (X, z, r)
% fits the best circle by nonlinear least squares
% for true geometric distance.
%
% X: given points <X(i,1), X(i,2)>
% z, r: starting values for ellipse solution
%
% z, r: parameters for ellipse found

  u = [z(1), z(2) , r]'    % Starting values
  h = u;
  while norm(h)>norm(u)*1e-6,
    a = u(1)-X(:,1); b = u(2)-X(:,2);
    fak = sqrt(a.*a + b.*b);
    J = [a./fak b./fak -ones(size(a))];  
    f = fak -u(3);
    h = -J\f;
    u = u + h;
  end;
  z = u(1:2); r = u(3);

end % circle
