3
$\begingroup$

Using WhenEvent inside Module is quite strange. The local variables are not evaluated in WhenEvent. For example

eq = Module[{time1 = 200, time2 = 400},
  {WhenEvent[t > time1, a[t] -> 1],
   WhenEvent[t > time2, a[t] -> 0]}]

returns

{WhenEvent[t > time1$1064, a[t] -> 1], 
 WhenEvent[t > time2$1064, a[t] -> 0]}

I guess it has something to do with the attribute of the WhenEvent?

Attributes[WhenEvent]
(* {HoldAll, Protected} *)

Is there anyway to force the local variables in WhenEvent to be evaluated?

$\endgroup$
2
  • $\begingroup$ Yes, it's related to HoldAll: Module[{a = 1}, Hold@a]. $\endgroup$
    – xzczd
    May 9, 2020 at 6:58
  • $\begingroup$ @xzczd how can I solve this problem then? $\endgroup$
    – 407PZ
    May 9, 2020 at 7:03

1 Answer 1

5
$\begingroup$

Yes, it's related to HoldAll, so, just Evaluate:

Module[{time = 200}, WhenEvent[t > time // Evaluate, a[t] -> 1]]

Alternatively, use With instead:

With[{time = 200}, WhenEvent[t > time, a[t] -> 1]]

To understand the behavior of With you may want to read:

What are the use cases for different scoping constructs?

$\endgroup$

Your Answer

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

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