# JMathLabTutorial:Statistics (Data Fitting)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Contents

# Data fitting

In this example we will perform non-linear regression. Assume data can be described by $y = A*\exp(-((x-x0)/\sigma)^2)$. Find the best parameters A,x0,sigma and display the results.

First, let us draw data with errors and overlay a function:

function y=fit(a,x) % build function to fit data
y=a(1)*exp(-(x-a(2)).^2/a(3)^2); end;

x = 0:0.5:10; % build data
for i=1:length(x),y(i)=1.5*exp(-(x(i)-4)^2/2)+rand(1)/5-0.1; end;
e = 0.1 * ones( 1, length(x) );  % errors

errorbar(x,y,e,'+'); % draw error bars
hold
xi=0:0.1:10;
yi=fit([ 1.4912  3.9911  1.4481 ],xi);
plot(xi,yi,'g');
plot(x,y,'r*');

This code plots data with error bars and a function "fit" with the parameters

[ 1.4912  3.9911  1.4481 ].


Here is other example:

function y=fit(a,x) % build function to fit data
y=a(1)*exp(-(x-a(2)).^2/a(3)^2); end;

x = 0:0.5:10; % build data
for i=1:length(x),y(i)=1.5*exp(-(x(i)-4)^2/2)+rand(1)/5-0.1; end;
e = 0.1 * ones( 1, length(x) );	 % errors

d=fit([1.4 4.0 0.5],5) % testing function
printf('%f',d)