6 views (last 30 days)

Hi something is wrong with my for loop i have no idea what to do

% write a program that will explore population dynamics

% The population dynamics of a community can be described by:

% dp/dt = G(Pmax - P(t))*P(t)

% Use Euler's Method to determine the population (") as a function of time (#)

% Plot the population (") as a function of time (#) from t = 0 to t = 20 years

% Use the following values for constants in the differential equation:

% pmax = 10,000

% G = 0.00005

% Use an initial condition of p = 800 when t=0

%% set perameters

pmax = 10000

G = 0.00005

tmin = 0

tmax = 20

Nx = 50

t = linspace(tmin, tmax, Nx)

dt = t(1)-t(0)

p = zeros(1,Nx)

p(0) = 800

%% calculate p values using euler method

p(1) = G*(pmax - p(0))*p(0)*dt+p(0)

for ip = 1:Nx

p(ip+1) = G*(pmax - p(t(ip))*p(t(ip))*dt+p(t(ip))

end

Geoff Hayes
on 21 Sep 2020

Kelsey - there are a couple of coding mistakes with the above. Before the code can execute, there is an error

Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for

mismatched delimiters.

with the line

p(ip+1) = G*(pmax - p(t(ip))*p(t(ip))*dt+p(t(ip))

becaue there is a missing closing bracket. The above line should be

p(ip+1) = G*(pmax - p(t(ip))*p(t(ip))*dt+p(t(ip)));

Next, there is the error

Array indices must be positive integers or logical values.

with the line

dt = t(1)-t(0)

As the error message indicates, positive integers or logical values must be used as indices. 0 is not a positive integer, so you if you want to find the delta, then just do

dt = t(2)-t(1)

Similarly, you must change

p(0) = 800

%% calculate p values using euler method

p(1) = G*(pmax - p(0))*p(0)*dt+p(0)

for ip = 1:Nx

to

p(1) = 800

%% calculate p values using euler method

p(2) = G*(pmax - p(1))*p(1)*dt+p(1)

for ip = 2:Nx

The final problem will be with

p(ip+1) = G*(pmax - p(t(ip))*p(t(ip))*dt+p(t(ip)));

and the error

Array indices must be positive integers or logical values.

because of p(t(ip)) where you are using the vaues of t - which are not integers - as indices into p. What is this code trying to do here?

James Tursa
on 21 Sep 2020

Edited: James Tursa
on 21 Sep 2020

p(ip) is the value of p at time t(ip). p isn't a function that you are passing time into like you are doing with p(t(ip)). So get rid of that t(ip) subscripting and simply use ip subscripting instead. E.g.,

p(ip+1) = G*(pmax - p(ip))*p(ip)*dt + p(ip);

Also, the initial condition is p = 800, and the initial value is p(1), so replace that p(1) line with simply

p(1) = 800;

and get rid of the p(0) = 800 line since 0 is not a valid subscript.

Which also means that the dt calculation should be this:

dt = t(2) - t(1);

James Tursa
on 21 Sep 2020

James Tursa
on 22 Sep 2020

Opportunities for recent engineering grads.

Apply TodayFind the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
## 0 Comments

Sign in to comment.