Test file for NonlinearFit.m

<< NonlinearFit.m

?NonlinearFit

Create a model with two Gaussian peaks

pars = {I1,w1,x1,I2,w2,x2};
pars0 = {1.,0.6,0.,1.5,0.4,1.2};
f[x_,{I1_,w1_,x1_,I2_,w2_,x2_}]=
  I1 Exp[-((x-x1)/w1)^2] + I2 Exp[-((x-x2)/w2)^2]

plot1 = Plot[f[x,pars0],{x,-1,3},DisplayFunction->Identity];

Data: perturb the original model a little

X = Table[x,{x,-1.,3.,0.1}];
data = {#,f[#,pars0]+Random[Real,{-0.1,0.1}]}& /@ X;

plot2 = ListPlot[data,DisplayFunction->Identity];

Do the actual fitting:

fitted = 
   NonlinearFit\
     [data,f[x,pars],
      pars,x,Errors->0.1,
      InitialGuess->pars0+Table[Random[Real,{-0.2,0.2}]],
        (* give not too easy initial values! *)
      ProgressTrace->True]

plot3 = Plot[Release[f[x,pars]/.fitted],{x,-1,3},
             DisplayFunction->Identity,
             PlotStyle->Dashing[{0.01,0.01}]];

and plot it all together:

Show[plot1,plot2,plot3,
     DisplayFunction->$DisplayFunction,
     PlotLabel->"Original model, data and fitted model"];