How to do this problem?

조회 수: 3 (최근 30일)
Zifeng Qiu
Zifeng Qiu 2020년 7월 5일
답변: Alan Stevens 2020년 7월 5일
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)

답변 (1개)

Alan Stevens
Alan Stevens 2020년 7월 5일
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

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by