I want to solve this simple equation with a event:

   sol = DSolve[{x'[t] == v[t], x[0] == 0, v[t] == 1, 
   WhenEvent[Evaluate[t == 2], {v[t] -> -v[t]}]}, {x[t], v[t]}, {t, 0,
   Plot[x[t] /. sol, {t, 0, 4}]

Help appreciated. Thanks.

  • $\begingroup$ Open up the documentation and read about NDSolve $\endgroup$
    – Sektor
    Apr 7, 2015 at 11:35
  • $\begingroup$ Can you give me a more specific answer. I guess it has to be something with using the highest order derivative inside the whenevent? $\endgroup$
    – pazduha
    Apr 7, 2015 at 11:53
  • $\begingroup$ After executing your code there are a bunch of error messages. Did you try to go after those ? $\endgroup$
    – Sektor
    Apr 7, 2015 at 12:02
  • $\begingroup$ v[t] == 2 does not make sense because it never happens. Lets say t==2 would be helpful, but I get this error: Unable to reinitialize the system at t = 2. within specified \ tolerances. $\endgroup$
    – pazduha
    Apr 7, 2015 at 12:21
  • $\begingroup$ @sektor Those errors are caused by DSolve not given a solution, i.e., the plot causes the messages, not the DSolve itself. It is that what needs to be solved. In principle WhenEvent should work for DSolve too, not only NDSolve. $\endgroup$ Apr 7, 2015 at 19:19

1 Answer 1


I think you are missing the option DiscreteVariables which tells NDSolve which of the variables have to be understood as discrete variables, that is variables which only change due to WhenEvents (see the documentation for DiscreteVariables for details). For those, you have to provide an initial condition (v[0]==1.) but no differential equation. The following code will do what I think you want:

sol = NDSolve[{
    x'[t] == v[t],
    x[0] == 0,
    v[0] == 1,
    WhenEvent[t == 2, v[t] -> -v[t]]
  {x[t], v[t]},
  {t, 0, 10},
  DiscreteVariables -> {v}

Plot[x[t] /. sol, {t, 0, 10}]
  • $\begingroup$ Thank you very much. This is exacly what I was missing! $\endgroup$
    – pazduha
    Apr 7, 2015 at 13:15

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.