Mathematics Previous page   Next Page

Fitting a Curve to Data

This section gives an example that shows how to fit an exponential function of the form A  times e to power minus lamba times t to some data. The example uses the function fminsearch to minimize the sum of squares of errors between the data and an exponential function for varying parameters A and lambda. This section covers the following topics.

Creating an M-file for the Example

To run the example, first create an M-file that

To do so, copy and paste the following code into an M-file and save it as fitcurvedemo in a directory on the MATLAB path.

The M-file calls the function fminsearch, which find parameters A and lambda that minimize the sum of squares of the differences between the data and the exponential function A*exp(-lambda*t). The nested function expfun computes the sum of squares.

Running the Example

To run the example, first create some random data to fit. The following commands create random data that is approximately exponential with parameters A = 40 and lambda = .5.

To fit an exponential function to the data, enter

This returns estimates for the parameters A and lambda,

and a function handle, model, to the function that computes the exponential function A*exp(-lambda*t).

Plotting the Results

To plot the fit and the data, enter the following commands.

The resulting plot displays the data points and the exponential fit.

Plot of data and best exponential fit on a single set of axes.

Previous page  Minimizing Functions of Several Variables Setting Minimization Options Next page

© 1994-2005 The MathWorks, Inc.