Use the \boxed{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.
10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | x |
260 | 236 | 195 | 150 | 136 | 98 | 76 | 63 | 52 | 49 | 48 | y |
r² | S | J | Degree n |
0.9197 | 54,168 | 4348 | 1 |
0.9997 | 58,318 | 197.9 | 2 |
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 \boxed{p \_first}, and the coefficients of the second degree polynomial are contained in the vector \boxed{p\_second}.
The results are \boxed{p \_first = [22.1909, 12.0455]}, which corresponds to the polynomial y = 22.1909x +12.0455, and \boxed{p \_second = [2.1993, 0.1979, 45.035]}, which corresponds to the polynomial y = 2.1993x² + 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 \boxed{polyfit (x,y,k)}. If you need the polynomial coefficients, say for the second-degree polynomial, type \boxed{polyfit(x,y,2)} after the program has been run.
The plots are shown in Figure C.2.1. The following table gives the values of J , S, and r² for each polynomial.
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.