% Example of least squares fitting
%
% Samuli Siltanen November 2012

% Plot parameters
msize  = 15;
fsize  = 16;
titlefsize = 20;
lwidth = 2;

% Choose amplitude of noise
noiselevel= 1;

% Choose parameters for the line
a = .8;
b = 10;

% Create ideal (y) and noisy (m) data
x = 10:1:100;
y = a*x+b;
m = y+noiselevel*randn(size(y));

% Plot the model, and ideal and noisy data 
figure(1)
clf
subplot(1,2,1)
plot(x,y,'k','linewidth',lwidth)
hold on
axis equal
set(gca,'ytick',[0:20:100],'fontsize',fsize)
set(gca,'xtick',[0:20:100],'fontsize',fsize)
box off
axis([0 110 0 100])
title(['Simulation of data: a=', num2str(a),' , b=', num2str(b)],'fontsize',titlefsize)



pause



plot(x,m,'r.','markersize',msize)



pause



% Plot the result of least squares fit (regression)
subplot(1,2,2)
plot(x,m,'r.','markersize',msize)
hold on
axis equal
set(gca,'ytick',[0:20:100],'fontsize',fsize)
set(gca,'yticklabel',{})
set(gca,'xtick',[0:20:100],'fontsize',fsize)
box off
axis([0 110 0 100])
pause
A = [x(:),ones(length(x),1)];
reg = A\m(:);
t = linspace(10,100,2);
plot(t,reg(1)*t+reg(2),'b','linewidth',lwidth)
plot(x,m,'r.','markersize',msize)
title(['Least squares fit: a=',num2str(round(1000*reg(1))/1000), ', b=', num2str(round(1000*reg(2))/1000)],'fontsize',titlefsize)

