Open In App

polyfit() in MATLAB

Last Updated : 18 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Polyfit is a function in MATLAB that fits a polynomial to a set of data points. It takes in three arguments:

x: a vector of x-coordinates of the data points
y: a vector of y-coordinates of the data points
n: the degree of the polynomial

polyfit returns a vector of coefficients representing the fitted polynomial in descending order. In this article, we will explore the polyfit function in MATLAB and how it can be used to fit a polynomial to a set of data points.

The syntax for polyfit is as follows:

Syntax:

p = polyfit(x,y,n)

where x and y are vectors of the same length representing the x- and y-coordinates of the data points, respectively, n is the degree of the polynomial, and p is a vector of coefficients representing the fitted polynomial in descending order.
 

Suppose we have the following data points:

(1,2) (2,3) (3,4)

We can use polyfit to fit a polynomial to these points. For example:

Example 1:

Matlab




x = [1 2 3];
y = [2 3 4];
p = polyfit(x,y,1)


Output:

p = 1.0000  1.0000

 

Explanation:

This means that the fitted polynomial is of degree 1 (a straight line) and has the following form:

y = x + 1

We can use polyval, another built-in function in MATLAB, to evaluate this polynomial at a specific point x. For example:

Example 2:

Matlab




x = 2;
y = polyval(p,x)


Output:

3.0000

 

This means that the value of the fitted polynomial at x = 2 is 3, which is the same as the original data point.

Multiple Degrees

We can also fit polynomials of a higher degree to the data points. For example, to fit a quadratic polynomial (degree 2). In MATLAB, the polyfit function can be used to fit a polynomial of any degree to a set of data points. The degree of the polynomial is specified as the third argument to the polyfit function.

Example 3:

Matlab




x = [1 2 3];
y = [2 3 4];
p = polyfit(x,y,2)


Output:

p = -0.0000    1.0000    1.0000

 

Conclusion:

In conclusion, polyfit is a useful function in MATLAB for fitting a polynomial to a set of data points. It is simple to use and can save time when working with polynomials in your code.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads