load lsq_eg1.dat
xd=lsq_eg1(:,1);
yd=lsq_eg1(:,2);
figure(1)
plot(xd,yd,'O:')

% LINE FIT ax + b
% solve the system of equations for the parameters
n=length(xd);
M=[sum(xd.^2) sum(xd); sum(xd) n];
beta=[sum(xd.*yd); sum(yd)];
M\beta
% Matlab's least squares fitting command
linecoeff=polyfit(xd,yd,1)
% plot the fit line overlaid on the data points
xp=linspace(0,7,100);
yp=polyval(linecoeff,xp);
figure(2)
plot(xd,yd,'O',xp,yp,'r','linewidth',2)

% QUADRATIC FIT ax^2 + bx + c
% solve the system of equations for the parameters
M=[sum(xd.^4) sum(xd.^3) sum(xd.^2); 
    sum(xd.^3) sum(xd.^2) sum(xd);
    sum(xd.^2) sum(xd) n];
beta=[sum(xd.^2.*yd); sum(xd.*yd); sum(yd)];
M\beta
% Matlab's least squares fitting command
quadcoeff=polyfit(xd,yd,2)
% plot the fit parabola overlaid on the data points
yp2=polyval(quadcoeff,xp);
figure(3)
plot(xd,yd,'O',xp,yp2,'r','linewidth',2)

% evaluate root-mean-square error of the fits
yf1=polyval(linecoeff,xd);
E2line=sqrt( sum((yd-yf1).^2)/n )
yf2=polyval(quadcoeff,xd);
E2quad=sqrt( sum((yd-yf2).^2)/n )
