% Least squares polynomial fitting (following Matlab v. 6.5
% section 12 example) L Braile, March 2005
% PolynomialFitLS.m
% enter x and y data
x = [0 .3 .8 1.1 1.6 2.3]';
y = [0.5 0.82 1.14 1.25 1.35 1.40]';
% set up the function of the form y = b0 + b1*x +b2*x^2
X = [ones(size(x)) x x.^2];  % the ones are used for the 
% constant (b0) term
b = X\y  % solve using the Matlab backslash operator
% plot the data and polynomial
xt = [0:0.1:2.5]';
yt = [ones(size(xt)) xt xt.^2]*b; % calculate theoretical values of
% y to plot the least squares quadratic curve
plot(xt,yt,'-',x,y,'or') % plot data and LSQ quadratic curve fit
title('2nd degree polynomial least squares fit to y = b0 + b1*x +b2*x^2')
xlabel('x')
ylabel('y')
