The polyfit
routine has the following syntax
p = polyfit(x,y,n)
where x
and y
are vectors of the same size, and
n
is the degree of the approximating polynomial.
The resulting vector p
forms the coefficients of
the optimal polynomial (in descending degree) that fit
y
with x
.
The polyfit
routine finds the approximating polynomial
such that
is minimized. It does so by forming the Vandermonde matrix and solving the resulting set of equations using the backslash operator. Note that the Vandermonde matrix can become poorly conditioned with large
n
quite rapidly.
A classic example from Edwards and Penny, consider the problem of approximating a sinusoid with a polynomial. We start with a vector of points evenly spaced on the unit interval, along with a vector of the sine of these points.
--> x = linspace(0,1,20); --> y = sin(2*pi*x); --> plot(x,y,'r-')
The resulting plot is shown here
Next, we fit a third degree polynomial to the sine, and use
polyval
to plot it
--> p = polyfit(x,y,3) p = <double> - size: [1 4] Columns 1 to 2 21.9170418782353 -32.8755628173530 Columns 3 to 4 11.1897267234139 -0.115602892148147 --> f = polyval(p,x); --> plot(x,y,'r-',x,f,'ko');
The resulting plot is shown here
Increasing the order improves the fit, as
--> p = polyfit(x,y,11) p = <double> - size: [1 12] Columns 1 to 2 12.4643875255456 -68.5541313918184 Columns 3 to 4 130.055546752557 -71.0939749422162 Columns 5 to 6 -38.2813761899149 -14.1222200242114 Columns 7 to 8 85.1017727524665 -0.564166385379567 Columns 9 to 10 -41.2861451730128 -0.00293966260467875 Columns 11 to 12 6.283246741110284 -1.26090310495983e-09 --> f = polyval(p,x); --> plot(x,y,'r-',x,f,'ko');
The resulting plot is shown here