% DeathProcess3.m simulates the 'pure death process'. Starting with
% nstart individuals, each having probability p of dieing in each
% time step, we continue until all have died. 
%
% The inner for-loop runs multiple simulations with the same
% value of starting population size (nstart) and death probability
% p, and computes the mean and standard deviation of extinction times
% 
% The outer loop varies the starting population size N0. At the end,
% the mean extinction time is plotted as a function of N0


%vectors to hold mean & std dev of extinction times
mtimes=zeros(5,1);
stimes=zeros(5,1);

% starting sizes
nstarts=100*(1:5)

for istart=1:5

% vector to hold extinction times
etimes=zeros(500,1);

for irep=1:500 

  % parameters
  nstart=nstarts(istart); p=0.1;

  %initialize variables for current population size
  nnow=nstart; nbarnow=nstart; t=0;

  % initialize vectors storing the results over time
  nt=nstart; nbar=nstart; tvals=0;

  while nnow>0;
  % update the stochastic population	
	m=rand(nnow,1);
	ndie=sum(m<p);
	nnow=nnow-ndie;
	nbarnow=(1-p)*nbarnow;
   % store the results
   	t=t+1;
	tvals=[tvals;t];
	nt=[nt;nnow];
	nbar=[nbar;nbarnow];
  end; 

  etimes(irep)=t;
  disp([istart irep])

end;

mtimes(istart)=mean(etimes);
stimes(istart)=std(etimes);

end; 

plot(nstarts,stimes/mtimes)
   
	



