%Ranleslie2.m - Math 151 
%This is to illustrate the effect of random environment
% on a Leslie Population growth model, consisting of 3
% age classes in which the fecundity of the last age class
% varies randomly. The model simulates the Population 
% for 20 years, then computes the growth rate for each
% year of the population for another 81 years and finds the 
% geometric mean of these growth rates. It saves this mean
% growth rate along with the population size at time 100. 
% This is repeated 200 times and histograms of the population
% size at time 101 are produced, along with histograms of the 
% geometric mean growth rate. This version does not use the geomean 
% function of Matlab but computes the geometric mean using
% its definition.
% P is the projection matrix and n0 is the
% initial population structure, ni is the population
% structure at time i, nitot is the total population size 
% at time i
% deviation gives how much below and above the average 
% fecundity f the random fecundity can be. Note that 
% deviation cannot be larger than f, the average fecundity.
q=101
deviation=1.
f=5.
n0=[40;35;25]
n0tot=sum(n0)
fmin=f-deviation
gm=[ ];
popsize=[ ];
for j=1:200
nstart=n0;
growthi=[ ];
for i=1:q
fran=fmin+rand(1,1)*deviation;
P=[0  1  fran; .5 0 0 ; 0 .26 0];
ni=P*nstart;
nitot=sum(ni);
nstart=ni;
if i >= 21
   growthi = [ growthi (nitot-n0tot)/n0tot ];
  else
end;
n0tot=nitot;
end;
j,n0tot
growthi=1.+growthi;
gm1=(prod(growthi))^(1./(length(growthi)));
gm=[gm gm1];
popsize=[popsize n0tot];
end;
disp('Mean and Standard Deviation of population size at 101 is')
mean(popsize),std(popsize),pause
disp('Mean and Standard Deviation of Geometric growth rates is')
mean(gm),std(gm),pause
hist(popsize)
title('histogram of population size at time 101'),pause
hist(gm)
title('histogram of geometric growth rates'),pause

