Section: Optimization and Curve Fitting
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.
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.
--> 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 3 21.91704187823530603 -32.87556281735295727 11.18972672341394770 Columns 4 to 4 -0.11560289214814741 --> 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 3 1.2464387525545638e+01 -6.8554131391818444e+01 1.3005554675255738e+02 Columns 4 to 6 -7.1093974942216235e+01 -3.8281376189914866e+01 -1.4122220024211366e+01 Columns 7 to 9 8.5101772752466474e+01 -5.6416638537956687e-01 -4.1286145173012805e+01 Columns 10 to 12 -2.9396626046787507e-03 6.2832467411102844e+00 -1.2609031049598294e-09 --> f = polyval(p,x); --> plot(x,y,'r-',x,f,'ko');
The resulting plot is shown here