I want to solve a system of coupled ODEs using NDSolve with WhenEvent. But I'm having a hard time trying to index the state vector x[i][t] inside NDSolve.

Here is my code (wrong indexing for x[i][t]):

n = 2; a = 1.1;
vars = Table[x[i][t], {i, n}];
eqns = Table[x[i]'[t] == a - x[i][t], {i, n}];
initcond = Table[x[i][0] == 0.3*i, {i, n}];
sol = NDSolve[
   {eqns, initcond,
     x[i][t] == 1,
     x[i][t] -> 0]},
   vars, {t, 0, 10}
Plot[Evaluate[vars /. sol], {t, 0, 10}, PlotRange -> All]

I want to reset any x[i][t] to 0 when it reaches 1. Is there an automatic way to do it? Thanks in advance!

  • $\begingroup$ Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! $\endgroup$ – Michael E2 Jul 10 '16 at 3:21

You need to construct an event for each i from 1 to n:

Block[{n = 2, a = 1.1},
 vars = Table[x[i], {i, n}];
 eqns = Table[x[i]'[t] == a - x[i][t], {i, n}];
 initcond = Table[x[i][0] == 0.3*i, {i, n}];
 evts = Table[With[{i = i}, WhenEvent[x[i][t] == 1, x[i][t] -> 0]], {i, n}];
 sol = NDSolve[{eqns, initcond, evts}, vars, {t, 0, 10}];

Plot[Evaluate[Through[vars[t]] /. sol], {t, 0, 10}, PlotRange -> All]

Mathematica graphics

(Since WhenEvent is HoldAll, we have to inject the value of i with With[{i = i},...]. See the section "Scope" in the docs for With.

| improve this answer | |
  • $\begingroup$ The code works now! Thank you so much for solving my problem! $\endgroup$ – B. Chen Jul 10 '16 at 12:27
  • $\begingroup$ As a record, we can also get around the hold issue by WhenEvent @@@ Table[{x[i][t] == 1, x[i][t] -> 0}, {i, n}] $\endgroup$ – luyuwuli Oct 15 '18 at 8:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.