%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function workshop01
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% plot and solve deterministic  logistic equations.
% For APM
% Eli Tziperman
close all; clear all

% set parameters for logistic equation: X_t=R*X*(1-X/K)
R=0.1;
K=50;

% plot logistic function:
plot_logistic(R,K); pause

% solve deterministic system:
X_simulate_deterministic=integrate_deterministic_logistic_eqn(R,K); pause

%--- end of main program ---%


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function X_simulate_deterministic=integrate_deterministic_logistic_eqn(R,K);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
tspan=[0:1:2500];
X0=3;
[T,X] = ode45(@(t,X) mylogistic(t,X,R,K),tspan,X0);
figure
plot(T,X)
% plot only for part of the simulation:
V=axis; axis([0 500 V(3) V(4)]);
title('solution of deterministic logistic eqn');
xlabel('time');
ylabel('N');
X_simulate_deterministic=X;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plot_logistic(R,K);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
t=0;
N=[0:0.1:K]; k=0;
for ii=N;
  k=k+1;
  Bplot(k)=B(N(k),R,K);
  Dplot(k)=D(N(k),R,K);
  Lplot(k)=mylogistic(t,N(k),R,K);
end;
figure
plot(N,Bplot,'g'); 
hold on
plot(N,Dplot,'b'); 
plot(N,Lplot,'r'); 
xlabel('N'); legend('B','D','logistic');


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function b=B(X,R,K)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% birth
if X<0
  b=0;
else
  b=R*X;
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function d=D(X,R,K)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% death
d=R*X^2/K;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function rhs=mylogistic(t,X,R,K)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
rhs= B(X,R,K)-D(X,R,K);

