% --------------------------------- 
% cubic_fit.m
% cubic 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,x.^2,x.^3];
% least square fit coefficients c 
c=A\y;
%define inline function f(x)
%f=@(x) c(1)+c(2)*x+c(3)*x.^2+c(4)*x.^3; 
f=@(x) [ones(N,1),x,x.^2,x.^3]*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 oder polynomial (=line)
ypoly=polyval(cpoly,x); % evaluate polynomial at points x
plot(x,ypoly,'go');  
xx=linspace(min(x),max(x),10*N)'; % more points
plot(xx,[ones(10*N,1),xx,xx.^2,xx.^3]*c,'m-'); 