Monday, June 28, 2010

curve fit in Matlab

1) Polynomial fit:
in polynomial.m
----------------------------------------
function polynomial
c=[1 2 -1] % for x*x+2*x-1
x=-1:0.1:1
y=polyval(c,x) % y=x*x+2*x-1
noise = rand(1, size(y,2)) %create some noise
newy=y+noise
newc=polyfit(x, newy,2) % get fit parameter
yc=polyval(newc,x)
hold on % plot all plots in 1 figure
plot(x, y, 'b--') % plot original blue --
plot(x, newy, 'r+') %plot new data with noise red ++
plot(x, yc, 'g') % plot fit curve green
legend('original curve','Data','Polynomial Fit','Location','NW')
---------------------------------------------------------
2. Non linear fit, for example Gaussian fit
define gauss.m
-----------------------------
function f=gauss(a,x)
f=a(1)*exp(-(((x-a(2))/a(3))/a(3)).^2)
-------------------------------------------------
then
-----------------------------------------
a=[2 0.5 1] % guess a
a=nlinfit(x,newy,'gauss',a) % find fit parameters for data [x, newy]
plot(x,gauss(a,x),'k') % plot fitted Gaussian curve in black

No comments:

Post a Comment