%% definisco la retta y=mx+q

m = 0.5;

q = 1.0;

x = 0:0.1:5;
x = x';

y = m*x+q;

y_noise = y + randn(length(y),1)*0.5;
figure;
plot(x,y);
hold on
plot(x,y_noise,'r+')
hold off
legend('original','noise','Location','SouthEast')


%% FITTING

A = [x, ones(length(x),1)];

c = inv(A'*A)*A'*y_noise;

m_fit = c(1);

q_fit = c(2);

y_fit = m_fit*x + q_fit;


figure;
plot(x,y);
hold on
plot(x,y_noise,'r+')
plot(x,y_fit,'g-')

hold off
legend('original','noise','fit','Location','SouthEast')

errore_original = sum((y-y_noise).^2)
errore_fit = sum((y_fit-y_noise).^2)