MATLAB: Does polyfit require data in x and y to be monotonically increasing

MATLABplotpolyfitpolyval

I am using "polyfit" to fit a polynomial to my data and then I visualize the result with "plot" after evaluating the polynomial at my data points with "polyval." The plot does not look right: it looks all scrambled instead of looking like an injective function.
My data is not monotonically increasing and I suspect this is the cause. Therefore, I am wondering if "polyfit" requires the input data to be monotonically increasing (i.e., sorted)?

Best Answer

It does not matter to the "polyfit" function whether the input data is sorted or not. The underlying algorithm is a simple least square problem on a Vandermonde matrix (with QR decomposition). The coefficients of the polynomial found by "polyfit" might differ slightly if the order of the input points changes, but, as long as the input data points form a well-conditioned set of equations, the difference should not be significant.
 
First, a Vandermonde matrix is constructed from the input data points "x" and the degree of the polynomial "n". Then, the matrix is factored as QR (orthogonal Q and upper triangular R). Finally, the system of equations is solved using "Q", "R" and the observations "y".
 
The script attached below (test_polyfit.m) shows the difference between a polynomial obtained when sorting the input data and a polynomial obtained without sorting the data. Both polynomials have degree 6.
 
Note that the data has to be sorted when calling "plot". The "plot" function draws straight lines between adjacent points in the input. If the inputs to "plot" are not rearranged so that "x" is increasing, it will draw something that does not make sense here.
 
If you are trying to fit a polynomial of higher degree, it might be necessary to center and scale the input data. Also, I noticed that some x-values are redundant. This can lead to a poorly conditioned system.