Skip to Main Content Skip to Search
Home |   United Kingdom  Choose Country  |  Contact Us  |  Cart Store 
Create Account | Log In
Products & Services Industries Academia Support User Community Company

 

Product Support

1504 - Fitting a Function to Data Using LSQNONLIN


This example illustrates how to use LSQNONLIN to fit the function,

f = A + B*exp(C*x) + D*exp(E*x)
      

to the X and Y data sets, where Y is the expected output given X. To do this, create the following function named fit_simp.m which uses the X and Y data, both of which are passed into lsqnonlin as optional input arguments. Use the X data to calculate values for f, and subtract the original Y data from this. The results are the differences between the experimental data and the calculated values. The lsqnonlin function will minimize the sum of the squares of these differences.

function diff = fit_simp(x,X,Y)
% This function is called by lsqnonlin.
% x is a vector which contains the coefficients of the
% equation.  X and Y are the option data sets that were
% passed to lsqnonlin.

A=x(1); B=x(2); C=x(3); D=x(4); E=x(5); diff = A + B.*exp(C.*X) + D.*exp(E.*X) - Y;

The following script is an example of how to use fit_simp.m:

% Define the data sets that you are trying to fit the
% function to.
X=0:.01:.5;
Y=2.0.*exp(5.0.*X)+3.0.*exp(2.5.*X)+1.5.*rand(size(X));

% Initialize the coefficients of the function. X0=[1 1 1 1 1]';
% Set an options file for LSQNONLIN to use the % medium-scale algorithm options = optimset('Largescale','off');
% Calculate the new coefficients using LSQNONLIN. x=lsqnonlin(@fit_simp,X0,[],[],options,X,Y);
% Plot the original and experimental data. Y_new = x(1) + x(2).*exp(x(3).*X)+x(4).*exp(x(5).*X); plot(X,Y,'+r',X,Y_new,'b')
Contact support
E-mail this page
Print this page