How to do this problem?
3 views (last 30 days)
Show older comments
I am trying to solve this problem about population dynamics. It's asking me to model the population base on the model and the function that I wrote before, but it doesn't seem to work, what did I do wrong? The
function [tv, uv] = RK4(f, u0, T, n) % This is Runge Kutta 4th order time-stepping function
dt = T/n; % Differential of time.
tv = transpose(0:dt:T); % Evaluation times.
uv = zeros(n+1, 1); % Solution.
uv(1) = u0; % Initial value
for i=1:length(tv)-1
k1 = f(tv(i), uv(i))
k2 = f(tv(i) + (dt/2), uv(i) + dt*k1/2)
k3 = f(tv(i) + (dt/2), uv(i) + dt*k2/2)
k4 = f(tv(i) + dt, uv(i) + dt*k3)
uv(i+1) = uv(i) + dt/6*[k1+2*k2+2*k3+k4]
end
end
u0 = 5000; % This is the code that I wrote
lambda = 0.03;
pm = 9000;
k = 100;
f = @(t,p) lambda*p*(1-p./pm)-k
pf = RK4(f,u0,10,100)
0 Comments
Answers (1)
Alan Stevens
on 5 Jul 2020
Try this:
u0 = 5000; % This is the code that I wrote
lambda = 0.03;
pm = 9000;
k = 100;
f = @(t,p) lambda*p*(1-p./pm)-k;
[t, pf] = RK4(f,u0,100,10); % T is 100, n is 10
plot(t,pf)
function [tv, uv] = RK4(f, u0, T, n) % This is Runge Kutta 4th order time-stepping function
dt = T/n; % Differential of time.
tv = transpose(0:dt:T); % Evaluation times.
uv = zeros(n+1, 1); % Solution.
uv(1) = u0; % Initial value
for i=1:length(tv)-1
k1 = f(tv(i), uv(i));
k2 = f(tv(i) + (dt/2), uv(i) + dt*k1/2);
k3 = f(tv(i) + (dt/2), uv(i) + dt*k2/2);
k4 = f(tv(i) + dt, uv(i) + dt*k3);
uv(i+1) = uv(i) + dt/6*(k1+2*k2+2*k3+k4);
end
end
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!