1
$\begingroup$

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}]

enter image description here

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.`.

$\endgroup$
4
$\begingroup$

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}]

Mathematica graphics

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

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.