function [c,r]=spherefit(X,draw)                % code by jph
%syntax:   [C,R]=SPHEREFIT(X,DRAW)
% X is of size [m n] and contains m points of dimension n.
% C is the center, and R is the radius of the fitting sphere.
% If DRAW is specified and n==2, the result is plotted.
%example:  [c,r]=spherefit(randn(7,2),1)

n=size(X,2);
A=[2*X ones(size(X,1),1)];

if rank(A)<n+1
  c=[];
  r=Inf;
  return;
end

a=A\sum(X.*X,2);
c=a(1:end-1);
r=sqrt(a(end)+c'*c);

if nargin>1&&n==2
  plot(X(:,1),X(:,2),'r*'); 
  hold on; axis equal;
  plot(c(1),c(2),'bx');
  t=linspace(0,2*pi);
  plot(r*cos(t)+c(1),r*sin(t)+c(2),'b');  
  hold off;
end
