# How to index multi-dimensional vectors in NDSolve/WhenEvent?

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,
WhenEvent[
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!

• 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! Commented Jul 10, 2016 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]


(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.

• The code works now! Thank you so much for solving my problem! Commented Jul 10, 2016 at 12:27
• As a record, we can also get around the hold issue by WhenEvent @@@ Table[{x[i][t] == 1, x[i][t] -> 0}, {i, n}] Commented Oct 15, 2018 at 8:48