%% Nonlinear Least Squares with Nondefault Options
% Compare the results of a data-fitting problem when using different lsqnonlin algorithms.
% Suppose that you have observation time data xdata and observed response data ydata, and you want to find parameters x(1) and x(2) to fit a model of the form
%  \hbox{ydata} = x(1)\exp\left(x(2)\hbox{xdata}\right).
%
% Input the observation times and responses.

xdata = ...
 [0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3];
ydata = ...
 [455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5];

%
% Create a simple exponential decay model. The model computes a vector of differences between predicted values and observed values.

fun = @(x)x(1)*exp(x(2)*xdata)-ydata;

%
% Fit the model using the starting point x0 = [100,-1]. First, use the default 'trust-region-reflective' algorithm.

x0 = [100,-1];
options = optimoptions(@lsqnonlin,'Algorithm','trust-region-reflective');
x = lsqnonlin(fun,x0,[],[],options)

%
% See if there is any difference using the 'levenberg-marquardt algorithm.

options.Algorithm = 'levenberg-marquardt';
x = lsqnonlin(fun,x0,[],[],options)

%
% The two algorithms found the same solution. Plot the solution and the data.

plot(xdata,ydata,'ko')
hold on
tlist = linspace(xdata(1),xdata(end));
plot(tlist,x(1)*exp(x(2)*tlist),'b-')
xlabel xdata
ylabel ydata
title('Exponential Fit to Data')
legend('Data','Exponential Fit')
hold off

% Copyright 2015 The MathWorks, Inc.