function CircleFitting

cx = 0.3;
cy = 0.5;
r = 1;

theta = 0:0.1:2*pi+0.1;
theta = theta';
x = cos(theta) + cx + 0.05*randn(size(theta));
y = sin(theta) + cy + 0.05*randn(size(theta));

A = [2*(x(2:end)-x(1)) 2*(y(2:end)-y(1))];
b = x(2:end).^2-x(1)^2 + y(2:end).^2-y(1)^2;
u = A\b;
dist = [x y] - ones(size(x)) * [u(1) u(2)];
dist = dist';
dist = mean(sqrt(sum(dist.^2)));
dist;

figure(1)
clf;
plot(x,y ,'b.');
hold on
plot(r*cos(theta)+cx, r*sin(theta)+cy, 'k--');
hold on
plot(dist*cos(theta)+u(1), dist*sin(theta)+u(2), 'r-');
hold on
plot(cx, cy, 'k+');
hold on
plot(u(1), u(2), 'r+');
grid on
axis equal

