\section{POLYFIT Fit Polynomial To Data}

\subsection{Usage}

The \verb|polyfit| routine has the following syntax
\begin{verbatim}
  p = polyfit(x,y,n)
\end{verbatim}
where \verb|x| and \verb|y| are vectors of the same size, and
\verb|n| is the degree of the approximating polynomial.  
The resulting vector \verb|p| forms the coefficients of
the optimal polynomial (in descending degree) that fit
\verb|y| with \verb|x|.  
\subsection{Function Internals}

The \verb|polyfit| routine finds the approximating polynomial
\[
   p(x) = p_1 x^n + p_2 x^{n-1} + \dots + p_n x + p_{n+1}
\]
such that
\[
   \sum_{i} (p(x_i) - y_i)^2
\]
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 \verb|n| quite rapidly.
\subsection{Example}

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.
\begin{verbatim}
--> x = linspace(0,1,20);
--> y = sin(2*pi*x);
--> plot(x,y,'r-')

\end{verbatim}
The resulting plot is shown here


\centerline{\includegraphics[width=8cm]{polyfit1}}

Next, we fit a third degree polynomial to the sine, and use
\verb|polyval| to plot it
\begin{verbatim}
--> p = polyfit(x,y,3)
p = 
  <double>  - size: [1 4]
 
Columns 1 to 3
  21.91704187823533800  -32.87556281735300701   11.18972672341396901  
 
Columns 4 to 4
  -0.11560289214815114  
--> f = polyval(p,x);
--> plot(x,y,'r-',x,f,'ko');

\end{verbatim}
The resulting plot is shown here


\centerline{\includegraphics[width=8cm]{polyfit2}}

Increasing the order improves the fit, as
\begin{verbatim}
--> p = polyfit(x,y,11)
p = 
  <double>  - size: [1 12]
 
Columns 1 to 4
 1.2464387511303785e+01  -6.8554131311258885e+01  1.3005554655396099e+02  -7.1093974663600378e+01  
 
Columns 5 to 8
 -3.8281376437475764e+01  -1.4122219880724931e+01  8.5101772697717465e+01  -5.6416637185701446e-01  
 
Columns 9 to 12
 -4.1286145175046236e+01  -2.9396624377344871e-03  6.2832467411045743e+00  -1.2608708173169825e-09  
--> f = polyval(p,x);
--> plot(x,y,'r-',x,f,'ko');

\end{verbatim}
The resulting plot is shown here


\centerline{\includegraphics[width=8cm]{polyfit3}}

