Nonlinear Curve Fitting with lsqcurvefit

lsqcurvefit enables you to fit parameterized nonlinear functions to data easily. You can use lsqnonlin as well; lsqcurvefit is simply a convenient way to call lsqnonlin for curve fitting.

In this example, the vector xdata represents 100 data points, and the vector ydata represents the associated measurements. Generate the data using the following script:

rng(5489,'twister') % reproducible
xdata = -2*log(rand(100,1));
ydata = (ones(100,1) + .1*randn(100,1)) + (3*ones(100,1)+...

The modeled relationship between xdata and ydata is


The script generates xdata from 100 independent samples from an exponential distribution with mean 2. It generates ydata from Equation 10-14 using a = [1;3;2], perturbed by adding normal deviates with standard deviations [0.1;0.5;0.5].

The goal is to find parameters a^i, i = 1, 2, 3, for the model that best fit the data.

In order to fit the parameters to the data using lsqcurvefit, you need to define a fitting function. Define the fitting function predicted as an anonymous function:

predicted = @(a,xdata) a(1)*ones(100,1)+a(2)*exp(-a(3)*xdata); 

To fit the model to the data, lsqcurvefit needs an initial estimate a0 of the parameters. Enter

a0 = [2;2;2];

Run the solver lsqcurvefit as follows:

[ahat,resnorm,residual,exitflag,output,lambda,jacobian] =...

Local minimum possible.

lsqcurvefit stopped because the final change in the
sum of squares relative to its initial value is
less than the default value of the function tolerance.

To see the resulting least-squares estimate of a^, enter:


ahat =

The fitted values ahat are within 8% of a = [1;3;2].

If you have Statistics and Machine Learning Toolbox™ software, use the nlparci function to generate confidence intervals for the ahat estimate.

Was this topic helpful?