lotka-voltter method euler
Afficher commentaires plus anciens
Hi,
I want to do lotka-voltter method euler
I have code but it is so slow, do not know how to add to
for loop y(i,2) y(i,1)
%%sta
a=1.2;
b=0.6;
c=0.4;
d=0.8;
e=1.0;
f=1.2;
%%R
f = @(t,y) [y(1)*(a - b*y(2))-e*y(1); y(2)*(c*y(1)-d)-f*y(2)];;
y= [2 2];
t=0;
h=0.01;
for i=1:5000
figure(2),plot(t,y(1),'b.',t,y(2),'r.'); hold on;
xlabel('time')
ylabel('populacja')
legend('x', 'y')
ylim([0 15])
xlim([0 50])
title('Lotka-Voltery')
s=f(t,y)
y=y+h*s;
t=t+h;
end
1 commentaire
Torsten
le 21 Jan 2019
Save t and y in a vector and plot outside the loop.
Réponses (1)
Running this code in each iteration is a waste of time:
figure(2),plot(t,y(1),'b.',t,y(2),'r.'); hold on;
xlabel('time')
ylabel('populacja')
legend('x', 'y')
ylim([0 15])
xlim([0 50])
title('Lotka-Voltery')
Run this once outside the loop.
figure(2)
axes('NextPlot', 'add'); % Equivalent to "hold on"
xlabel('time')
ylabel('populacja')
legend('x', 'y')
ylim([0 15])
xlim([0 50])
title('Lotka-Voltery')
y = zeros(2, 5000); % Pre-allocate
y(:, 1) = [2;2];
t = zeros(1, 5000);
for i = 2:5000
s = f(t(i-1), y(:, i-1));
y(:, i) = y(:, i-1) + h * s; % Collect all y values
t(i) = t(i-1) + h; % Collect all t values
end
plot(t, y(1, :),'b.', t,y(2, :), 'r.');
By the way: "lotka volterra"
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!