Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curve fitting in matlab

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??

like image 215
a d Avatar asked Nov 29 '12 19:11

a d


2 Answers

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,'-')
like image 165
Niclas Avatar answered Sep 21 '22 12:09

Niclas


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.

like image 29
mythealias Avatar answered Sep 22 '22 12:09

mythealias