%% Fit a Simple Exponential
% Fit a simple exponential decay curve to data.
% Generate data from an exponential decay model plus noise. The model is
%  y = \exp(-1.3t) + \varepsilon,
% with t ranging from 0 through 3, and \varepsilon normally distributed noise with mean 0 and standard deviation 0.05.

rng default % for reproducibility
d = linspace(0,3);
y = exp(-1.3*d) + 0.05*randn(size(d));

%
% The problem is: given the data (d, y), find the exponential decay rate that best fits the data.
% Create an anonymous function that takes a value of the exponential decay rate r and returns a vector of differences from the model with that decay rate and the data.

fun = @(r)exp(-d*r)-y;

%
% Find the value of the optimal decay rate. Arbitrarily choose an initial guess x0 = 4.

x0 = 4;
x = lsqnonlin(fun,x0)

%
% Plot the data and the best-fitting exponential curve.

plot(d,y,'ko',d,exp(-x*d),'b-')
legend('Data','Best fit')
xlabel('t')
ylabel('exp(-tx)')

% Copyright 2015 The MathWorks, Inc.