Contents Previous Next Subchapters

Least Squares Fit of a Descending Polynomial to Data
Syntax p = polyfit(xyn)
See Also lagrange , cubespl

Minimizes the linear least squares objective with respect to the polynomial coefficient vector p
       N                                          2
     -----  |           n               1        |
     >      | y  - p * x  - ... - p  * x  - p    |     
     -----  |  i    1   i          n    i    n+1 |
     i = 1
where N is the length of the vectors x and y. The arguments x and y are integer, real, double-precision or complex vectors with the same length. The argument n is scalar and equal to an integer value. The returned value p is a row vector with the type that results from coercion between the type of x and y (unless they are both integer in which case the return value is double precision).

The following example fits a third degree polynomial to a sine wave over the interval [-pi , +pi]. The example plots the data values with the symbol + an the fitted curve with a solid line (see the image below).

x = PI * (seq(21) - 11) / 10d0
y = sin(x)
n = 3
p = polyfit(x, y, n)
v = polyval(p, x)
gplot(x, y, "plus")
gplot(x, v, "solid")