1
$\begingroup$

I want to use Table or Array to generate a list of events for NDSolve, but the variables (gap[k]) in the rules of the events are not being assigned their values. Is there a simple way to modify this?

I found some answers related to my problem (here and here), but they don't seem to solve it.

Clear["Global`*"];

nk = 3;
Table[gap[k] = k, {k, nk}];

Table[With[{ki = k},
{WhenEvent[f[ki][t] == 0, {c[ki][t] -> d[ki][t] + gap[ki]}]}],{k, 1, nk}]

Array[
 {WhenEvent[x[#][t] == 0, {c[#][t] -> d[#][t] + gap[#]}],
   WhenEvent[y[#][t] == 0, {c[#][t] -> d[#][t] + gap[#]}]} &, nk]

update1 : my problem vs. problem here

If I understand right, the answer here is to use Evaluate to force computation of variables in the event. But in my problem, using Evaluate on variable gap[k] is not working. Please check the result of the following code.

Table[With[{ki = k}, {WhenEvent[Evaluate@gap[ki] + f[ki][t] == 0, 
{c[ki][t] -> d[ki][t] + Evaluate@gap[ki]}]}], {k, 1, nk}]
$\endgroup$
6
  • $\begingroup$ Another related post: mathematica.stackexchange.com/q/221480/1871 And, you should have put more effort in understanding the answer you've received: mathematica.stackexchange.com/a/298317/1871 $\endgroup$
    – xzczd
    Commented Sep 7 at 6:19
  • $\begingroup$ @xzczd Thanks for your help as always. I tried to show that why my problem is different from the answer your suggsted. Please see the update. $\endgroup$
    – xinxin guo
    Commented Sep 7 at 9:21
  • $\begingroup$ …Your update clearly shows you don't understand the linked answers and the usage of Evaluate: Table[With[{ki = k}, {WhenEvent[ Evaluate[gap[ki] + f[ki][t] == 0], {c[ki][t] -> d[ki][t] + Evaluate@gap[ki]}]}], {k, 1, nk}] As mentioned in Details section of document of Evaluate: "Evaluate only overrides HoldFirst etc. attributes when it appears directly as the head of the function argument that would otherwise be held. " $\endgroup$
    – xzczd
    Commented Sep 7 at 9:22
  • $\begingroup$ @xzczd Thanks, now I see the difference. I agreed to close this post. Or maybe it is better to delete this post? Have a nice day, thanks. $\endgroup$
    – xinxin guo
    Commented Sep 7 at 9:25
  • $\begingroup$ Since now there's an upvoted answer, I don't think you're able to delete it :) . Just keep it as a road sign. $\endgroup$
    – xzczd
    Commented Sep 7 at 9:32

1 Answer 1

2
$\begingroup$

This is because function WhenEvent has attribute HoldAll:

Attributes[WhenEvent]

(*{HoldAll, Protected}*)

To solve this problem, you need to map Evaluate to WhenEvent at the second argument, like

Table[With[{ki = k}, {MapAt[Evaluate, 
    WhenEvent[f[ki][t] == 0, {c[ki][t] -> d[ki][t] + gap[ki]}], 
    2]}], {k, 1, nk}]

(*{{WhenEvent[f[1][t] == 0, {c[1][t] -> 1 + d[1][t]}]}, {WhenEvent[
   f[2][t] == 0, {c[2][t] -> 2 + d[2][t]}]}, {WhenEvent[
   f[3][t] == 0, {c[3][t] -> 3 + d[3][t]}]}}*)
$\endgroup$
0

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