function LineFitting

m = 1.2;
d = 0.3;

x = 4*(rand(100,1)-.5);
y = m*x + d + randn(size(x));

A = [x ones(size(x))];
b = y;

u = A\b;

[u_m u_d] = meshgrid(m-0.5:0.01:m+0.5, d-0.5:0.01:d+0.5);
U = 0;
for i = 1 : size(x,1)
    U = U + (A(i,1)*u_m + A(i,2)*u_d - y(i)).^2;
end

figure(2)
clf;
surfc(m-0.5:0.01:m+0.5, d-0.5:0.01:d+0.5,U, 'LineStyle', 'none');
xlabel('m');
ylabel('d');
hold on
colormap(jet)

figure(3)
clf;
contourf(m-0.5:0.01:m+0.5, d-0.5:0.01:d+0.5,U,100, 'LineStyle', 'none');
hold on
plot(m,d,'kx');
xlabel('m');
ylabel('d');
hold on
colormap(jet)

figure(1)
clf;
plot(x,y, 'b.');
hold on
x0 = -2.5;
x1 = 2.5;
y0 = m*x0+d;
y1 = m*x1+d;
plot([x0 x1], [y0 y1], 'k--');

x0 = -2.5;
x1 = 2.5;
y0 = u(1)*x0+u(2);
y1 = u(1)*x1+u(2);
plot([x0 x1], [y0 y1], 'r-');
grid on
axis([-3 3 -3 3]);
axis equal
legend('Data point', 'Ground truth line', 'Fitted line');
