MATLAB Function Reference    

Polynomial curve fitting



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 produces error bounds that contain at least 50% of the predictions.

[p,S,mu] = polyfit(x,y,n) finds the coefficients of a polynomial in

where and . mu is the two-element vector . This centering and scaling transformation improves the numerical properties of both the polynomial and the fitting algorithm.


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.


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

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

You can modify the M-file to use other functions of as the basis functions.

See Also

poly, polyval, roots

  polyeig polyint