How do I fit experimental data?

This howto will show you an example of how to import, fit, and visualize experimental data.

Import and graphing the data set

Use the Import command to import the data set. Mathematica automatically detects that the file is in table format and returns it as a list of lists.

\(\(data\  = \ 
        Import["C:\desk\Demos 10-30ff\How tos\juliep\gauss2.dat"];\)\)

Notice the semicolon at the end of the command. Without the semicolon suppressing the output, a list of all 250 data points would be printed into the notebook.

Mathematica provides the ListPlot function for plotting experimental data.

dataplot = ListPlot[data];

Perform a nonlinear fit on the data set

The functions for performing nonlinear fits in Mathematica are in the statistics package NonlinearFit.m. Before calculating the fit, the package has to be loaded into memory.

<< Statistics`NonlinearFit`

The first argument to NonlinearFit is the data set; the second is the model; the third is the independent variables of the model; the fourthis the parameters of the fit. In this particular case the model is

y = a (e^(-b x))+ c (e^(((-(((x - d))^2))/(e^2))))+ f (e^(((-(((x - g))^2))/(h^2)))),

with the independent variable x, and the parameters a,  b,  c,  d,  e,  f,  
      g,  h.

fitdata = 
      NonlinearFit[data, 
        a* Exp[-b*x] + c*Exp[((-(((x - d))^2))/(e^2))] + 
          f*Exp[((-(((x - g))^2))/(h^2))], 
        x,  {{a, 94.9}, {b, 0.009}, {c, 90.1}, {d, 113.0}, {e, 20.0}, {f, 
            73.8}, {g, 140.0}, {h, 20.0}}]

Graph the fit to the data

Notice that the output from the fit above was an equation.

fitplot = 
        Plot[fitdata, {x, 1, 250}, 
          PlotStyle -> RGBColor[1, 0, 0]];

To plot both the data set and the fit together, use Show.

bothplots = Show[dataplot, fitplot];

Performing a regression analysis

NonlinearRegress, in the same package as NonlinearFit, provides a complete regression analysis in addition to the fit parameters. Be warned that computing the orthogonal complement of an 8 x 250 matrix for quantities needed by FitCurvatureTable and ParameterBias can be lengthy. In this case 15 seconds on a 300MHz Pentium II. To avoid the wait, omit FitCurvatureTable and ParameterBias from the items specified by RegressionReport. The postfix //TableForm  formats the results nicer than the standard output option.

regdata = 
      NonlinearRegress[data, 
          a* Exp[-b*x] + c*Exp[((-(((x - d))^2))/(e^2))] + 
            f*Exp[((-(((x - g))^2))/(h^2))], 
          x,  {{a, 94.9}, {b, 0.009}, {c, 90.1}, {d, 113.0}, {e, 20.0}, {f, 
              73.8}, {g, 140.0}, {h, 20.0}}] // TableForm