%FITDEMO Nonlinear curve fit with simplex algorithm.

%	Copyright (c) 1984-93 by The MathWorks, Inc.

clf
echo on
clc
%	This example demonstrates fitting a nonlinear function to a
%	set of data.  We'll use a function called FMINS that implements
%	the Nelder-Mead simplex algorithm for minimizing a nonlinear
%	function of several variables.

pause  % Press any key to continue.
clc
%	Consider the following data:

global Data

Data = ...
  [ 0.0000    5.8955
    0.1000    3.5639
    0.2000    2.5173
    0.3000    1.9790
    0.4000    1.8990
    0.5000    1.3938
    0.6000    1.1359
    0.7000    1.0096
    0.8000    1.0343
    0.9000    0.8435
    1.0000    0.6856
    1.1000    0.6100
    1.2000    0.5392
    1.3000    0.3946
    1.4000    0.3903
    1.5000    0.5474
    1.6000    0.3459
    1.7000    0.1370
    1.8000    0.2211
    1.9000    0.1704
    2.0000    0.2636];

pause	% Strike any key to continue.

clc
%	Let's plot this data.

t = Data(:,1);
y = Data(:,2);
axis([0 2 0 6])
hold on
plot(t,y,'co','EraseMode','none')
title('Input data')

pause	% Strike any key to continue.

clc
%	We would like to fit the function
%
%	  y =  c(1)*exp(-lam(1)*t) + c(2)*exp(-lam(2)*t)
%
%	to the data.  This function has 2 linear parameters
%	and 2 nonlinear parameters.  Here it is.
type fitfun

%	To fit this function to the data, we write a function, called
%	say FITFUN, that, given the nonlinear parameters lam and the data,
%	returns the error in the fit.  We can then guess for initial
%	estimates of the nonlinear parameters, and invoke FMINS.

pause	% Strike any key to start fitting.

global Plothandle
Plothandle = plot(t,y,'y-','EraseMode','xor');

lam = [1 0]'; 
trace = 0;
tol = .1;
lambda = fmins('fitfun',lam,[trace tol]);

hold off
echo off
s = ['lambda = fmins(''fitfun'',[1 0]'',[0 .1]);'];
uicontrol('Units','normal','Position',[.2 .01 .1 .06],'String','Again','callback',s)

disp('End')
