1
$\begingroup$

I came across an error when using a list of Discrete Variables with NDSolve and WhenEvent. As you can see in the minimal example, where I defined the 'testevent', when I use x[[1]] -> x1[t] + 1 , everything works as it should. However, if I use x[[1]] -> x[[1]] + 1 instead, I get the error message "NDSolve: "The function value {1+x1[t]} is not a list of numbers with
dimensions {1} when the arguments are
{0.2,1.2000000000000004,1.4000000000000001,1.6,1.,1.,1.`}". Does anyone know what lies behind this error and how to get around it? This is a minimal example of a code where I would like to use a quite long/adaptable long list of discrete variables, for which it would be tedious to explicitly right down each variable in the WhenEvent.

Thanks in advance!

This version works:

Clear["Global`*"];
Off[Solve::ifun]
tmax = 1;
u = {u1[t], u2[t], u3[t]};
x = {x1[t], x2[t], x3[t]};
eq = Table[D[u[[i]], t] == i*x[[i]], {i, 1, 3}];
init = Flatten[{Table[u[[i]] == 1 , {i, 1, 3}], 
     Table[x[[i]] == 1, {i, 1, 3}]} /. t -> 0];
testevent = 
  WhenEvent[Mod[t, 0.2] == 0, {Print[t], x[[1]] -> x1[t] + 1}];
sol = NDSolve[Flatten[{eq, init, testevent}], {u, x}, {t, 0, tmax}, 
    DiscreteVariables -> x][[1]];
solu = Thread[sol[[1, 1]] -> sol[[1, 2]]];
solx = Thread[sol[[2, 1]] -> sol[[2, 2]]];
GraphicsRow[{Plot[Evaluate[u /. solu], {t, 0, tmax}],
  Plot[Evaluate[x /. solx], {t, 0, tmax}]}]

This version does not work:

Clear["Global`*"];
Off[Solve::ifun]
tmax = 1;
u = {u1[t], u2[t], u3[t]};
x = {x1[t], x2[t], x3[t]};
eq = Table[D[u[[i]], t] == i*x[[i]], {i, 1, 3}];
init = Flatten[{Table[u[[i]] == 1 , {i, 1, 3}], 
     Table[x[[i]] == 1, {i, 1, 3}]} /. t -> 0];
testevent = 
  WhenEvent[Mod[t, 0.2] == 0, {Print[t], x[[1]] -> x[[1]] + 1}];
sol = NDSolve[Flatten[{eq, init, testevent}], {u, x}, {t, 0, tmax}, 
    DiscreteVariables -> x][[1]];
solu = Thread[sol[[1, 1]] -> sol[[1, 2]]];
solx = Thread[sol[[2, 1]] -> sol[[2, 2]]];
GraphicsRow[{Plot[Evaluate[u /. solu], {t, 0, tmax}],
  Plot[Evaluate[x /. solx], {t, 0, tmax}]}]
$\endgroup$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.