clear
clf
x=0:6
% generate data according to y=x.^2 + noise for x values 0,1,...6
y=x.^2 + 3*randn(1,length(x))

plot(x,y,'*')

% this is the way to set up the A matrix (x values as the first column)
% 1's as the second column (check above to see that this is so )
A = [ x' ones(length(x),1)]

mb= A\y'


xp=0:.1:6
yp=mb(1)*xp +mb(2)

hold on
plot(xp,yp)

%% when we want to fit y=mx+nx^2 + b we set up the A matrix as below
%% 1st column has the x values, 2nd column the xvalues squared, last column 1's
A = [ x' x.^2' ones(length(x),1)]
mnb=A\y'

xp=0:.1:6
yp=mnb(1)*xp +mnb(2)*xp.^2+ mnb(3)



plot(xp,yp,'r')


%This is a better fit.  What if we take this further
%Here we try to fit

%y=mx + nx^2 +px^3 + b

%% by adding another column to A we can fit more complex functions
%% this fits y=mx+nx^2+px^3+b
A = [ x' x.^2' x.^3' ones(length(x),1)]
mnpb=A\y'

xp=0:.1:6
yp=mnpb(1)*xp +mnpb(2)*xp.^2+ mnpb(3)*xp.^3 + mnpb(4)

plot(xp,yp,'g')


%How about 
%y=mx+nx^2 +px^3 + qx^4 + rx^5+b

A = [ x' x.^2' x.^3' x.^4' x.^5' ones(length(x),1)]
mnpqrb=A\y'

xp=0:.1:6
%% computing the ypoints to plot is exactly analogous to the simpler cases above
yp=mnpqrb(1)*xp +mnpqrb(2)*xp.^2+ mnpqrb(3)*xp.^3 + mnpqrb(4)*xp.^4 + mnpqrb(5)*xp.^5 + mnpqrb(6)

plot(xp,yp,'k')
