Reputation: 572
For example i have 5 point like this,
(1,1) (2,-1) (3,2) (4,-2) (5,2)
Now,
How can I do this??
Upvotes: 6
Views: 11291
Reputation: 1230
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,'-')
Upvotes: 9
Reputation: 350
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.
Upvotes: 3
Reputation: 276
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]
Upvotes: 1