%% Optimal Fit of a Non-linear Function
% This is a demonstration of 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.
%
% Modified by VdS from program fitdemo by
% Copyright 1984-2004 The MathWorks, Inc.
% $Revision: 5.15.4.2 $ $Date: 2004/08/16 01:37:29 $

%%
% First, create some sample data and plot it.

x = (0:.1:2)';
y = [5.8955 3.5639 2.5173 1.9790 1.8990 1.3938 1.1359 1.0096 1.0343 ...
     0.8435 0.6856 0.6100 0.5392 0.3946 0.3903 0.5474 0.3459 0.1370 ...
     0.2211 0.1704 0.2636]';
plot(x,y,'ro'); hold on; h = plot(x,y,'b'); hold off;
title('Input data'); ylim([0 6])

%%
% The goal is to fit the following function with three linear parameters and one
% nonlinear parameter to the data:
%
%     y =  ax + bx^2 + c*exp(-d*x) + e
%
% To fit this function, we've create a function MYFITFUNSLOW.  Given the
% parameters a b c d and e and the data (x and y), FITFUN calculates the error in the
% fit for this equation and updates the line (h).

type myfitfunslow

%%
% Make a guess for initial estimate of a b c d and e (start) and invoke FMINSEARCH.  It
% minimizes the error returned from FITFUN by adjusting them.  It returns the
% final value of a b c d and e.

start = [-2; 1; 4; 1; 2];
options = optimset('TolX',0.1);  % termination tolerance on x 
estimated_abcde = fminsearch(@(abcde) myfitfunslow(abcde,x,y,h),start,options)

