% logisticV2.m
%
% Numerically integrate a 1D ODE (the Logistic Equation) using the
% Runge-Kutta 45 solver and and compare the result to the analytic solution
%
% Logistic equation:  dx/dt = a * x * (1 - x)
%
% New to Version 2:  
%    - set tolerances
%    - plot ODE solution against the analytic solution
%    - plot numerical error
%
% MATLAB-Monkey.com   9/29/2013


function logisticV2
a = 2;          % free parameter

tBegin = 0;     % time begin
tEnd = 10;      % time end

x0 = 0.001;     % initial position

% Use the Runge-Kutta 45 solver to solve the ODE
% Set relative and absolute tolerances
options = odeset('RelTol', 1e-3, 'AbsTol', 1e-6);
[t,x] = ode45(@derivatives, [tBegin tEnd], x0, options);

% Analytic Solution
x2 = x0 ./ ((1-x0) * exp(-a*t) + x0);


%%%%%  top plot:  solutions
subplot(2,1,1)      % top plot
plot(t,x,'ro');     % plot ode45 solution as red circles    
hold on             % superimpose next plot on previous
plot(t,x2,'b-');    % plot analytic solution as blue line
ylim([0 1.2]);      % set y plot limits

title('Solution to the Logistic Equation');             % title
xlabel('time');                                         % label x axis
ylabel('Monkey Population');                            % label y axis
legend('rk45', 'analytic', 'Location', 'Northwest')     % legend top left


%%%%%  lower plot:  error
subplot(2,1,2)                      % lower plot          
plot(t,x-x2,'b-')                   % plot error as blue line
title('Numerical Error');           % Title
xlabel('time');                     % label x axis
ylabel('x_{rk45}-x_{analytic}');    % label y axis


% print to pdf
set(gcf, 'PaperSize', [6 6]);  
set(gcf, 'PaperPosition', [0 0 6 6]);  
print ('-dpdf','logisticV2.pdf');
print ('-dpng','logisticV2.png','-r100');


    %%%%%  Function: derivatives
    % returns the derivative dx/dt for the logistic equation
    % uses the parameter a from main program, but changeth it not
    function dxdt = derivatives(t,x)
        dxdt = a * x * (1 - x);
    end

end
