Question C.3.1: Use the polyfit function to find the first- and second-degre...
Use the polyfit function to find the first- and second-degree polynomials that fit the following data in the least-squares sense. Evaluate the quality of fit for each polynomial.
\begin{array}{l|lllllllllll}x & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\\hline y & 48 & 49 & 52 & 63 & 76 & 98 & 136 & 150 & 195 & 236 & 260\end{array}
The following MATLAB program computes the polynomial coefficients.
% Enter the data.
x = (0:10);
y = [48, 49, 52, 63, 76, 98, 136, 150, 195, 236, 260];
% Fit a first-degree polynomial.
p_first = polyfit(x,y,1)
Fit a second-degree polynomial.
p_second = polyfit(x,y,2)
The polynomial coefficients of the first-degree polynomial are contained in the vector p_first, and the coefficients of the second-degree polynomial are contained in the vector p_second. The results are p_first = [22.1909, 12.0455], which corresponds to the polynomial y = 22.1909x+12.0455, and p_second = [2.1993, 0.1979, 45.035], which corresponds to the polynomial y = 2.1993x2 + 0.1979x + 45.035.
We can use MATLAB to plot the polynomials and to evaluate the “quality-of fit” quantities J, S, and r². The following script file does this.
% Enter the data and find the mean of y.
x = (0:10);
y = [48, 49, 52, 63, 76, 98, 136, 150, 195, 236, 260];
mu = mean(y);
% Define a range of x and y values for plotting.
xp = (0:0.01:10);
for k = 1:2
yp(k,:) = polyval(polyfit(x,y,k),xp);
% Compute J, S, and r squared.
J(k) = sum((polyval(polyfit(x,y,k),x)-y).ˆ2);
S(k) = sum((polyval(polyfit(x,y,k),x)- mu).ˆ2);
r2(k) = 1-J(k)/S(k);
end
% Plot the first-degree polynomial.
subplot(2,1,1)
plot(xp,yp(1,:),x,y,'o'),axis([0 10 0 300]),xlabel('x'),...
ylabel('y'),title('First-degree fit')
% Plot the second-degree polynomial.
subplot(2,1,2)
plot(xp,yp(2,:),x,y,'o'),axis([0 10 0 300]),xlabel('x'),...
ylabel('y'),title('Second-degree fit')
% Display the computed values.
disp('The J values are:'),J
disp('The S values are:'),S
disp('The rˆ2 values are:'),r2
The polynomial coefficients in the above script file are contained in the vector polyfit (x,y,k). If you need the polynomial coefficients, say for the second-degree polynomial, type polyfit(x,y,2) after the program has been run.
The plots are shown in Figure C.3.1. The following table gives the values of J, S, and r² for each polynomial.
\begin{array}{c|ccc}\text{Degree}n & J & S & r ^2 \\\hline 1 & 4348 & 54,168 & 0.9197 \\2 & 197.9 & 58,318 & 0.9997\end{array}
Because the second-degree polynomial has the largest r² value, it represents the data better than the first-degree polynomial, according to the r² criterion. This is also obvious from the plots.
