Main Content

Curve Fitting via Optimization

This example shows how to fit a nonlinear function to data. For this example, the nonlinear function is the standard exponential decay curve

y ( t ) = A exp ( - λ t ) ,

where y ( t ) is the response at time t , and A and λ are the parameters to fit. Fitting the curve means finding parameters A and λ that minimize the sum of squared errors

i = 1 n ( y i - A exp ( - λ t i ) ) 2 ,

where the times are t i and the responses are y i , i = 1 , , n . The sum of squared errors is the objective function.

Create Sample Data

Usually, you have data from measurements. For this example, create artificial data based on a model with A = 4 0 and λ = 0 . 5 , with normally distributed pseudorandom errors.

rngdefault% for reproducibilitytdata = 0:0.1:10; ydata = 40*exp(-0.5*tdata) + randn(size(tdata));

Write Objective Function

Write a function that accepts parametersAandλand datatdataandydata, and returns the sum of squared errors for the model y ( t ) . Put all the variables to optimize (Aandλ) in a single vector variable (x). For more information, seeMinimizing Functions of Several Variables.

typesseval
函数sse = sseval (x, tdata ydata) = x (1);λ= x(2); sse = sum((ydata - A*exp(-lambda*tdata)).^2);

Save this objective function as a file namedsseval.mon your MATLAB® path.

Thefminsearchsolver applies to functions of one variable,x. However, thessevalfunction has three variables. The extra variablestdataandydataare not variables to optimize, but are data for the optimization. Define the objective function forfminsearchas a function ofxalone:

fun = @(x)sseval(x,tdata,ydata);

For information about including extra parameters such astdataandydata, seeParameterizing Functions.

Find the Best Fitting Parameters

Start from a random positive set of parametersx0, and havefminsearchfind the parameters that minimize the objective function.

x0 = rand(2,1); bestx = fminsearch(fun,x0)
bestx =2×140.6877 0.4984

The resultbestxis reasonably near the parameters that generated the data,A = 40andλ= 0.5.

Check the Fit Quality

To check the quality of the fit, plot the data and the resulting fitted response curve. Create the response curve from the returned parameters of your model.

A = bestx(1); lambda = bestx(2); yfit = A*exp(-lambda*tdata); plot(tdata,ydata,'*'); holdonplot(tdata,yfit,'r'); xlabel(“tdata”) ylabel('Response Data and Curve') title('Data and Best Fitting Exponential Curve') legend('Data','Fitted Curve') holdoff

Figure contains an axes object. The axes object with title Data and Best Fitting Exponential Curve contains 2 objects of type line. These objects represent Data, Fitted Curve.

Related Topics