Clear Filters
Clear Filters

Is there an easy way to make numerical simulations of the ODE of the form dx1/dt=x1(2-x1-x2), dx2/dt=x2(3-x1-x2-x3) for any xn?

1 view (last 30 days)
I have tried doing for 'n=5' and here is my code;
dx = @(t,x) [x(1);
x(1)*(2-x(1)-x(2));
x(2); x(2)*(3-x(1)-x(2)-x(3));
x(3); x(3)*(3-x(2)-x(3)-x(4));
x(4); x(4)*(3-x(3)-x(4)-x(5));
x(5); x(5)*(2-x(4)-x(5))];
tspan=[0 15];
x0=[0 2 0 3 0 4 0 6 0 8];
[t,x] = ode45(@(t,x) dx(t,x), tspan, x0);
figure(1)
plot(t, x)
Can someone please check if this code is correct, if not, how can I improve if and for any 'n'?. Thanks in advance.

Accepted Answer

Abraham Boayue
Abraham Boayue on 5 Apr 2018
See code comments for answers.
clear variables
close all;
% dx must have 5 terms for n = 5
% the number terms in system equations
% must be the same as the number of
% elements in your dx vector.
% Remember your dot before *
dx = @(t,x) [x(1);x(1).*(2-x(1)-x(2));
x(2).*(3-x(1)-x(2)-x(3));
x(3).*(3-x(2)-x(3)-x(4));
x(4).*(3-x(3)-x(4)-x(5))];
tspan=[0 15];
x0=[0 2 0 3 0]; % same for the initial vector.
[t,x] = ode45(dx, tspan, x0);
figure(1)
plot(t, x);
  1 Comment
Editor
Editor on 6 Apr 2018
Thank you very much Abraham Boayue for your response and your code too does what I want. I have noted the mistakes I had made in my earlier code. However, is there a way in which this code can be be generalised to compute for any 'xn', say 'n=10'?.

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!