MATLAB Function Reference
  Go to function:
    Search    Help Desk 
polyfit    Examples   See Also

Polynomial curve fitting

Syntax

Description

p = polyfit(x,y,n) finds the coefficients of a polynomial p(x) of degree n that fits the data, p(x(i)) to y(i), in a least squares sense. The result p is a row vector of length n+1 containing the polynomial coefficients in descending powers:


[p,s] = polyfit(x,y,n) returns the polynomial coefficients p and a structure S for use with polyval to obtain error estimates or predictions. If the errors in the data Y are independent normal with constant variance; polyval will produce error bounds that contain at least 50% of the predictions.

Examples

This example involves fitting the error function, erf(x), by a polynomial in x. This is a risky project because erf(x) is a bounded function, while polynomials are unbounded, so the fit might not be very good.

First generate a vector of x-points, equally spaced in the interval ; then evaluate erf(x) at those points.

The coefficients in the approximating polynomial of degree 6 are

There are seven coefficients and the polynomial is


To see how good the fit is, evaluate the polynomial at the data points with

A table showing the data, fit, and error is

So, on this interval, the fit is good to between three and four digits. Beyond this interval the graph shows that the polynomial behavior takes over and the approximation quickly deteriorates.

Algorithm

The M-file forms the Vandermonde matrix, V, whose elements are powers of x.


It then uses the backslash operator, \, to solve the least squares problem

The M-file can be modified to use other functions of x as the basis functions.

See Also

polyval     Polynomial evaluation

roots       Polynomial roots



[ Previous | Help Desk | Next ]