If[ ] not evaluating properly inside NDSolve[ ]

I am trying to solve a set of equations with the NDSolve. I encounter an error which I try to explain it with the below example.

q[u_] := 1;

s = NDSolve[{

Sum[If[u == n[t], q[u], q[u] + 5], {u, 1}] y”[t] == -1000 y[t],
y'[0] == 0, y[0] == 1, n[0] == 1, WhenEvent[t > 3.5, n[t] -> 2]},

{y}, {t, 0, 7}, DiscreteVariables -> {n}];

Plot[y[t] /. s, {t, 0, 7}]

As you can see when q[u_] := 1 I have the result but when I define the q[u_] as a function of u, for example q[u_] := u which should give me the same result as the above figure, I recieve this error

Encountered non-numerical value for a derivative at t == 0.`.

=================

=================

1 Answer
1

=================

It’s a “problem” due to the holding attributes of If[ ]. You may inject the value
by using With[{pp=u},If[….]] inside your Sum[] or with something like this:

q[u_] := u

s = NDSolve[{
(Total[If[# == n[t], n[t] q[#] , q[#]] & /@ Range@2] ) y”[ t] == -100 y[t],
y'[0] == 0, y[0] == 1, n[0] == 1,
WhenEvent[t > 3.5, n[t] -> 2]}, {y, n}, {t, 0, 7},
DiscreteVariables -> {n}];

Plot[y[t] /. s, {t, 0, 7}]

1

 

Thank you so much. Both solutions work well. Sum[With[{u = u}, If[u == n[t], q[u], q[u] + 5]], {u, 1}]
– Ali
Jul 20 ’15 at 18:54