##### Sections
You are here: Home Example of Curve Fitting

# Example of Curve Fitting

Frequently, we'd like to examine how well a particular set of data fits a theoretical function. Microsoft Excel can perform curve fits for a limited number of functions (including power, polynomial, and logarithmic), but Matlab allows us to define our own function. The following document shows one way to fit data to a user-defined function.

This particular example tries to fit a set of experimental data to a variation on the error function (defined as: erf(x) = 2/sqrt(pi) * integral from 0 to x of exp(-t^2) dt). We use a numerical optimization function fminsearch which employs a Nelder-Mead simplex algorithm to find a local minimum for a given function and inputs.

## MATLAB Code

All the following MATLAB code files are stored in a single directory.

cfitdemo.m (main program):

```   global xdata ydata;
mydata=[0       0
2       0.00334053
6       0.18940438
10      0.81127045
16      2.62518105
20      3.72280151
26      4.78842375
30      5.13031049
36      5.29059507 ];
xdata=mydata(:,1);
ydata=mydata(:,2);
w_start=[3.5701 0.6662 1.10603 -1.7086];
options=optimset('MaxFunEvals',10e9);
w_guess=fminsearch('myfitfunc',w_start,options);
w0_guess=w_guess(1);
w1_guess=w_guess(2);
w2_guess=w_guess(3);
w3_guess=w_guess(4);
ystart=w_start(1)+(w_start(2)*(erf((w_start(3)*xdata)+w_start(4))));
yfit=w0_guess+(w1_guess*(erf((w2_guess*xdata)+w3_guess)));
plot(xdata,ydata,'ro',xdata,ystart,'g',xdata,yfit,'b');
legend('Original Data','Original Fit','Final Fit',4);
title(sprintf('Curve Fit Example: yfit=%.3f+(%.3f*erf((%.3f*x)+(%.3f)))', ...
w0_guess,w1_guess,w2_guess,w3_guess));
xlabel('x')
ylabel('y')
```

The array named `mydata` is a list of (x,y) coordinates for the experimental data. The global variables `xdata` and `ydata` represent just the x or y coordinates of the `mydata` list.

The `w_start` vector is a list of coefficients for our fit function. In this case, they're particularly poor guesses, but the optimization function manages to find a good fit despite them.

The `options` line sets the maximum number of loops for the optimization process. If the optimizer hasn't found a local minimum by the 10,000,000,000th try, it will return the best value it found so far.

The `w_guess` line uses the objective function below to evaluate the quality of fit to the data points. `w_guess` will be a set of coefficient values that result in a minimal deviation from the data.

The remaining lines plot the original data points and the fit function to visually show the quality of fit.

myfitfunc.m (user-defined function to test quality of fit):

```  function err=myfitfunc(w)
global xdata ydata;
w0=w(1);
w1=w(2);
w2=w(3);
w3=w(4);
yfit=w0+(w1*(erf((w2*xdata)+w3)));
err=norm(ydata-yfit);
```

## Results

At the MATLAB command prompt:

```  >> cfitdemo
>>
``` (Thanks to Saravanan Swaminathan for assisting in this documentation.)

Filed under: 