Curve fitting in matlab

10,519

Solution 1

To fit a polynom to given datapoints you can use polyfit(x,y,n) where x is a vector with points for x, y is a vector with points for y and n is the degree of the polynom. See example at Mathworks polyfit documentation

In your case:

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

And then to plot, taken from example

f = polyval(p,x);
plot(x,y,'o',x,f,'-')

Or, to make a prettier plot of the polynomial (instead of above plot)

xx=0:0.1:5;
yy = erf(xx);
f = polyval(p,xx);
plot(x,y,'o',xx,f,'-')

Solution 2

If you are not sure what a good fit would be and want to try out different fit, use the curve fitting toolbox, cftool. You will need to create two vectors with x and y coordinates and then you can play around with cftool.

Another option would be to use interp1 function for interpolation. See matlab documentation for more details.

Solution 3

If you want polynomial interpolation, take a look at the polyfit function. It is used generally for least-squares polynomial approximation, but if you choose the degree+1 to be the same as the number of points you are fitting it will still work for you. For interpolation as you probably know, the degree of the interpolant is equal to the number of points you have -1. So for your example points above you need a degree 4 polynomial. Here is a link to the mathworks documentation

http://www.mathworks.co.uk/help/matlab/ref/polyfit.html

If you split your points into 2 vectors of respective x and y coordinates, you can simply obtain your interpolating polynomial coefficients in a vector b where

  b = polyfit(x,y,4)

and based on your data above, your x and y vectors are

x = [1 2 3 4 5];
y = [1 -1 2 -2 2]
Share:
10,519
a d
Author by

a d

please delete me

Updated on June 04, 2022

Comments

  • a d
    a d almost 2 years

    For example i have 5 point like this,

    (1,1) (2,-1) (3,2) (4,-2) (5,2)
    

    Now,

    • 1) I want a function to interpolation these points in Matlab.
    • 2) I want to Plot this function.
    • 3) Read a number from input and write F(x) to output.

    How can I do this??