clc
clear all
close all

x=[0.000;0.500;1.000;1.5000;2.000;2.500;3.000]
y=[0.000;0.250;1.000;2.2500;4.000;6.250;9.000]

% circunferencia (x-x0)2+(y-y0)2-R2=0
% calculo da estimativa inicial dos parametros  
% x0 = media dos valores de x
% y0 = media dos valores de y
% R = distancia de um ponto qualquer a (x0,y0)

xmedio=0
ymedio=0
for i=1:7
    xmedio=xmedio+x(i);
    ymedio=ymedio+y(i);
end
xmedio=xmedio/7;
ymedio=ymedio/7;

R0=sqrt((x(1)-xmedio)^2+(y(1)-ymedio)^2);

delta=[xmedio;ymedio;R0]

% linearizando a equacao (x-x0)2+(y-y0)2-R2=0 tem-se:
% (x-x00)2+(y-y00)2-R02 - 2(x-x00)x0 - 2(y-y00)y0 - 2R0R
% onde x00, y00 R00 são valores iniciais dos parametros x0, y0 R

itera=1;
while (itera <=10)
    for i=1:7
        B(i,1)=-2*(x(i)-delta(1,1));
        B(i,2)=-2*(y(i)-delta(2,1));
        B(i,3)=-2*delta(3,1);
        f(i,1)=-(x(i)-delta(1,1))^2-(y(i)-delta(2,1))^2+delta(3,1)^2;
        i=i+1;
    end
    
    N=B'*B;
   
    t=B'*f;
    
    delta_acrescimo=inv(N)*t;
    
    delta=delta+delta_acrescimo;
    
    if (abs(delta_acrescimo(1)) < 0.001 & abs(delta_acrescimo(2)) < 0.001 & abs(delta_acrescimo(3)) < 0.001)
        break;
    end
      
    itera=itera+1;
end

itera

delta

fprintf('Equacao da circunferencia: (x - %.6f)**2 + (y - %.6f)**2 = %.6f**2\n', delta(1), delta(2), delta(3));

disp ('   ')

hold on

th = 0:pi/50:2*pi;
xunit = delta(3) * cos(th) + delta(1);
yunit = delta(3) * sin(th) + delta(2);
h = plot(xunit, yunit);

plot(x(1), y(1), 'r.', 'LineWidth', 2, 'MarkerSize', 25);
plot(x(2), y(2), 'r.', 'LineWidth', 2, 'MarkerSize', 25);
plot(x(3), y(3), 'r.', 'LineWidth', 2, 'MarkerSize', 25);
plot(x(4), y(4), 'r.', 'LineWidth', 2, 'MarkerSize', 25);
plot(x(5), y(5), 'r.', 'LineWidth', 2, 'MarkerSize', 25);
plot(x(6), y(6), 'r.', 'LineWidth', 2, 'MarkerSize', 25);
plot(x(7), y(7), 'r.', 'LineWidth', 2, 'MarkerSize', 25);

hold off

    






