Documentation |
Polynomial curve fitting
p = polyfit(x,y,n) returns the coefficients for a polynomial p(x) of degree n that is a best fit (in a least-squares sense) for the data in y. The coefficients in p are in descending powers, and the length of p is n+1
$$p(x)={p}_{1}{x}^{n}+{p}_{2}{x}^{n-1}+\mathrm{...}+{p}_{n}x+{p}_{n+1}.$$
[p,S] = polyfit(x,y,n) also returns a structure S that can be used as an input to polyval to obtain error estimates.
[p,S,mu] = polyfit(x,y,n) also returns mu, which is a two-element vector with centering and scaling values. mu(1) is mean(x), and mu(2) is std(x). Using these values, polyfit centers x at zero and scales it to have unit standard deviation
$$\widehat{x}=\frac{x-\overline{x}}{{\sigma}_{x}}\text{\hspace{0.17em}}.$$
This centering and scaling transformation improves the numerical properties of both the polynomial and the fitting algorithm.
In problems with many points, increasing the degree of the polynomial fit using polyfit does not always result in a better fit. High-order polynomials can be oscillatory between the data points, leading to a poorer fit to the data. In those cases, you might use a low-order polynomial fit (which tends to be smoother between points) or a different technique, depending on the problem.
Polynomials are unbounded, oscillatory functions by nature. Therefore, they are not well-suited to extrapolating bounded data or monotonic (increasing or decreasing) data.