Access Keys:
Skip to content (Access Key - 0)
 
More about this article
Created: 11/07/2008 10:33
Modified: 02/18/2009 01:28

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:

	x = [1 2 3 4 5 6 7 8];
	y = [1 4 9 16 25 36 49 64];

Then, to do the regression, you'd do something like:

	c = polyfit(x,y,3);

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:

	>>> c
	    0.0000    1.0000    0.0000   -0.0000

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 = polyval(c,x);

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:

	plot(x,y,x,newy)

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

      c = poly2fit(x,y,z,3)

returns the coefficients of the fitted polynomial in descending powers of x and y.

Your Rating: Results: PatheticBadOKGoodOutstanding! 3 rates

Adaptavist Theme Builder Powered by Atlassian Confluence