% Least squares polynomial fitting (following Matlab v. 6.5 % section 12 example) L Braile, March 2005 % PolynomialFitLS2.m Same as PolynomialFitLS.m except uses % polyfit and polyval % 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]'; P = polyfit(x,y,2) % find coefficients of least squares quadratic xt = [0:0.1:2.5]'; yt = polyval(P,xt); % calculate theoretical values of % y using polyval to plot the least squares quadratic curve yt2 = polyval(P,x); % calculate theoretical values at the x coordinates SSE = sum((y-yt2).^2) % calculate and print SSE 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')