Tutorial:JMathLab/Statistics (Data Fitting)

From HandWiki

Data fitting

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

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

<jc lang="math"> 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*'); </jc>

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

[ 1.4912  3.9911  1.4481 ].

Here is other example:

<jc lang="math"> 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) </jc>