This example shows the optimal fitting of a non-linear function to a set of data. It uses
fminsearch, an implementation of the Nelder-Mead simplex (direct search) algorithm, to minimize a nonlinear function of several variables.
The focus of this example is to fit the following function with two linear parameters and two nonlinear parameters to the data:
y = C(1)*exp(-lambda(1)*t) + C(2)*exp(-lambda(2)*t)
To fit this function, a function
st_fitfun was created. Given the nonlinear parameter (lambda) and the data (t and y),
st_fitfun calculates the error in the fit for this equation.
function [err, z] = st_fitfun(lambda,t,y) %ST_FITFUN Function fit used by SystemTest demo. % % [ERR, Z] = ST_FITFUN(LAMBDA, T, Y) returns the error between the data % and the values computed by the current function of lambda, as well as % the function output. % % FITFUN assumes a function of the form % % y = c(1)*exp(-lambda(1)*t) + ... + c(n)*exp(-lambda(n)*t) % % with n linear parameters and n nonlinear parameters. % Copyright 2006-2007 The MathWorks, Inc. % Silent the rank deficient warning. wmode = warning('off', 'MATLAB:rankDeficientMatrix'); % Calculate the error between the data and the values computed by the % current function of lambda. A = zeros(length(t), length(lambda)); for j = 1:length(lambda) A(:,j) = exp(-lambda(j)*t); end c = A\y; z = A*c; err = norm(z-y); % Reset the warning mode. warning(wmode);
Data To Fit
Using SystemTest, sample data is read in and plotted as part of the Pre Test section. This data is read in from an Excel file using the
xlsread function by using a MATLAB element.
For each Main Test iteration, different initial estimates of lambda are used by defining a test vector. These initial estimates are used to invoke
fminsearch which minimizes the error returned from
st_fitfun by adjusting and returning the final value of lambda.
Using an output function, intermediate fits are plotted for each Main Test iteration as well using a General Plot element.
Performing the Test
Using a Limit Check element, the error for each fit performed is checked to see if it meets a maximum error constraint. The data produced for each test iteration is also written out to the Excel file by using the
xlswrite function in a MATLAB element.
At the end of the test, the generated Excel file is opened to display the data generated during the test runs.
To view the test, use the
systemtest function to open the test.