Contents Previous Next Subchapters Current Chapters-> interp interp1 lagrange polyfit smospl cubespl cubeval interp2 mlmode_interp2 snewton brent linlsq linlsqb nlsq dnlsq nlsqbox dnlsqb conjdir neldermead conjgrad minline lemke Qpos Qbox Qpro sqp relative fordiff cendiff autodiff testder testgrad testhess Parent Chapters-> Omatrix6 fit polyfit Search Tools-> contents reference index search

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

Description
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).

Example
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). ``` clear 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") ``` ``` ```