How do I do polynomial regressions in MATLAB?
To do polynomial regressions in matlab, you need to use the "polyfit" function. To use it, you must enter your data into variables. For example:
Then, to do the regression, you'd do something like:
This would fit it to a third order polynomial; to have it fit to a higher order polynomial, you could just change the last argument to what you want.
Then to see the fit polynomials in the example above, you can just type the name of the variable:
These are the coefficients in descending power of x, of the n-th order polynomial that fits the vector y to x.
If you would like to plot both the data AND the result of fitting, you can use the polyval function to do so. Type:
newy will be the vector containing the values of X evalated using the coefficients of the polynomial that fits y to x. To plot both the data and the fitted data, type:
You can also find a polynomial in x and y that fits a given set of data using the "poly2fit" and "poly2val" commands. Usage of these commands is similar to "polyfit" and "polyval", except that x,y and z are matrices. You can use the "meshgrid" command to transform a domain specified by two vectors X and Y, into array form. Then
returns the coefficients of the fitted polynomial in descending powers of x and y.