polyfit

Least-squares polynomial fit to data.

Category: Mathematics > Elementary Math

Syntax

p = polyfit(x, y, n)

Returns the coefficients of the degree-n polynomial that best fits y as a function of x in the least-squares sense.

Description

The function builds the Vandermonde matrix of x and solves the over-determined system by QR factorization. With n+1 points the polynomial passes exactly through the data (interpolation); with more points it minimizes the sum of squared residuals.

High degrees are numerically fragile because powers of x become nearly dependent. Keep the degree low, or center and scale x before fitting.

Input arguments

x, y
Vectors of the same length: sample points and measured values.
n
Degree of the polynomial. It needs at least n+1 distinct points for a unique fit.

Output arguments

p
Row vector of n+1 coefficients, highest power first, ready for polyval.

Example

Line and parabola

x = [1 2 3 4];
y = [2 4 6 8.5];
p = polyfit(x, y, 1)
polyval(p, 5)
polyfit([0 1 2], [1 3 7], 2)
Output
p = 1×2

    2.1500   -0.2500
ans = 10.5000
ans = 1×3

    1.0000    1.0000    1.0000

See also

polyval polyder polyint roots interp1