Saving variables from functions to workspace and making the code recognize the function
Show older comments
I'm trying to implement a logistic growth stochastic simulation, with my code being split into 4 functions as shown below. I'm getting one error in the code saying that function simulation might be unused. I've tried calling the function in the usual way as:
[n_vec]=simulation();
But that gives an 'undefined function or variable 'simulation' error. Any tips on how to successfully run the function and save the resulting n_vec to the workspace? I'd also like to save variables like br or dr, but I assume I can apply the same method as would be suggested for n_vec to do it on my own.
The code is:
%n-population size
%b- per capita birth rate
%d- per capita death rate at low density
%m- controls strength of density dependence
%differential equation for a stochastic analogue simulation:
%dn/dt= (b-d)*n +m*(n^2)
%carrying capacity K= (b-d)/m
%Stochastic population will grow and then fluctuate around a
%value a bit lower than K, but at some time will go extinct
b=2; d=1; m=0.01;
params=[b d m];
function [br]=BirthRate(n,b)
br=b*n;
end
function [dr]= DeathRate(n,d,m)
dr=n*d+m*(n^2);
end
function [n]= timestep(n,delta_t)%params is specified in the function code
%delta_t is the time step
%params is a list containing population dynamic parameters,
%split into three columns:1- b, per capita birth rate,
%2- d, per capita death rate, 3- m strength of density
%params[:,1] is per capita birth rate
%params[:,2] is per capita death rate etc.
%Births
%mean number of births is br*delta_t, relised number is Poisson
%distributed with this mean
disp(n)
lambda= BirthRate(n,b)*delta_t;
pd = poissrnd(lambda);
n =n + pd;
disp(n)
% deaths
%for a survival process with probability per unit time of
%dying H, the probability of surviving delta_t is:
%ps- probability of surviving=exp(-H*delta_t)
%the number surviving is a binomial random number,
%with number of trials= population size and probability that
%each trial succeeds being the survival probability ps
%for each individual, probability of death per unit time is:
%pod=dr/n
p_survive=exp((-DeathRate(n, d, m)*delta_t)/n); %check if brackets are corrects
disp(p_survive)
n=binornd(n,p_survive); %binomial random numbers
end
%code to run the simulation
function [n_vec] = simulation() %n and params are specified in function, dont have to be added
n=10; %initial population size
n_vec=zeros(1,1000);
for i = 1:1:1000
n=timestep(n,0.02, params);
n_vec(i)=n;%adds the new(current) population size to the vector data
end
end
Accepted Answer
More Answers (0)
Categories
Find more on Binomial Distribution in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!