4
$\begingroup$

I have a system of differential equations with two discrete variables (var1 and var2) that can be either 0 or 1. I'm trying to obtain a numerical solution with NDSolve for such system. I want to be able to manipulate those discrete variables independently, i.e, make var1 = 0 at t = 3, and become 1 at t = 6, and back to 0 at t =9, and so on. I also want to make var2 = 0 at t = 4, and become 1 at t = 8, and back to 0 at t = 12, and so on.

My initial attempt looks like this

parameters = {..., periodvar1=3, periodvar2=4,...} 
solution = NDsolve[eqx,eqy,eqz,
                   WhenEvent[Mod[t,periodvar1], {var1[t] -> 0}],
                   WhenEvent[Mod[t,periodvar2], {var1[t] -> 1}],
                   WhenEvent[Mod[t,periodvar1], {var2[t] -> 0}],
                   WhenEvent[Mod[t,periodvar2], {var2[t] -> 1}],
                   x[0] = 1, y[0] = 1, z[0] =1, var1[0] =1, var2[0] =0} /.parameters,
                   {x[t], y[t],z[t]}, {t,0,100},
                   DiscreteVariables -> {var1,var2}];

I figured out that this approach keeps var1 = 1 and var2 = 1 for every t (It seems like the last WhenEvent prevails over the previous). I tried also something like:

WhenEvent[{Mod[t,periodvar1],var1==1}, {var1[t] -> 0}],
WhenEvent[{Mod[t,periodvar2],var1==0}, {var1[t] -> 1}],
WhenEvent[{Mod[t,periodvar1],var2==1}, {var2[t] -> 0}],
WhenEvent[{Mod[t,periodvar2],var2==0}, {var2[t] -> 1}],

And finally:

WhenEvent[{Sin[t*pi/periodvar1] >= 0, Sin'[t*pi/periodvar1] > 0}, var1[t] -> 1], 
WhenEvent[{Sin[t*pi/periodvar1] <= 0, Sin'[t*pi/periodvar1] < 0}, var2[t] -> 0],

But the result were either fixed var1 or error messages. Is there a clean way to do this? (To make the point clear, my example started with two variables but I aim to progressively add more variables so it should be extendable).

| improve this question | | | | |
$\endgroup$
3
$\begingroup$

No need of help. I figured it out by myself. This will do the work:

WhenEvent[Mod[t, periodvar1], var1[t] -> Switch[var1[t], 0, 1, 1, 0]],
...
WhenEvent[Mod[t, periodvarn], varn[t] -> Switch[varn[t], 0, 1, 1, 0]],

And at the end

DiscreteVariables -> {var1[t], ..., varn[t]}]
| improve this answer | | | | |
$\endgroup$

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.