% -----------------------------------
% linear_fit.m
% Linear least squares fit to data
% -----------------------------------
clear all ; close all;
% known data points; column vectors
N=5;
x=linspace(2,7,N)';
y=[2.1,6.8,12.2,17.4,21.6]';
% basis functions {1,x}, so n=2,linear fit 
% (N,n) = (5,2) = design matrix 
A=[ones(N,1),x];
% least square fit coefficients c 
c=A\y;
%define inline function f(x)
% f=@(x) c(1)+c(2)*x; % coefficient one by one, clumsy
%f=inline('A(x)*c','x');
f=@(x) [ones(N,1),x]*c;
plot(x,y,'rx',x,f(x));hold on;
title 'linear fit';xlabel 'x';ylabel 'y';
% same problem using built-in polyfit    
cpoly=polyfit(x,y,1);   % fit to 1st order polynomial (=line)
ypoly=polyval(cpoly,x); % evaluate polynomial at points x
plot(x,ypoly,'go');  
legend('original data','lsq line','polyfit result')
