% File: bifurcation.m
% Description: plots bifurcation diagram of model of population growth by RM May (1974)
% Author: Emily G. Allen
% Date: January 2008

% Inputs: 
%       rMin, rMax: range of rate values over which results should be
%       mapped
%       x0: initial population size (fractional value from 0 to 1.0)

% Outputs: pop: the bifurcation diagram

function [pop] = bifurcation(rMin, rMax, x0)
 
    numGens = 1000; % number of generations over which population growth is modeled
    pMax = 100; % number of end generations that should be examined for the long-run behavior
    n = 1000; % number of intervals overwhich bifurcations are calculated
    
    r = linspace(rMin, rMax, n); % creates an array of n evenly spaced values from rMin to rMax
    pop = zeros(pMax, n); % creates a 2-d array that has data for n rates and pMax generations
    
    % iterate over the n rates from rMin to rMax
    for k = 1:n
        x = popGrowth(r(k), numGens, x0, 0); % calculate the growth trajectory for the current rate
        pop(:,k) = x(numGens - pMax + 1:numGens); % update the bifurcation diagram with the last pMax elements of x
    end

    plot(r, pop, 'b.'); % plot the bifurcation diagram
   
    title(strcat('x0 = ', num2str(x0)));
    xlabel('Rate');
    ylabel('Long-run Value (Attractor)');