Polynomial Curve Fitting
This example shows how to fit a polynomial curve to a set of data using polyfit. Use the polyfit function to find the coefficients of a polynomial that fits a set of data in a least-squares sense using the syntax
p = polyfit(x,y,n),
- x and y are vectors containing the x and y data to be fitted
- n is the degree of the polynomial to return
Consider the x-y test data
x = [1 2 3 4 5]; y = [5.5 43.1 128 290.7 498.4];
Use polyfit to find a third-degree polynomial that approximately fits the data.
p = polyfit(x,y,3)
p = -0.1917 31.5821 -60.3262 35.3400
After you obtain the polynomial using polyfit, use polyval to evaluate the polynomial at other points that might not have been included in the original data.
Compute the values of the polyfit estimate over a finer domain and plot the estimate over the real data values for comparison.
x2 = 1:.1:5; y2 = polyval(p,x2); plot(x,y,'o',x2,y2) grid on