# Using WhenEvent

I want to solve this simple equation with a event:

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


Help appreciated. Thanks.

• Open up the documentation and read about NDSolve Apr 7, 2015 at 11:35
• Can you give me a more specific answer. I guess it has to be something with using the highest order derivative inside the whenevent? Apr 7, 2015 at 11:53
• After executing your code there are a bunch of error messages. Did you try to go after those ? Apr 7, 2015 at 12:02
• 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. Apr 7, 2015 at 12:21
• @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. Apr 7, 2015 at 19:19

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==1.) but no differential equation. The following code will do what I think you want:

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

Plot[x[t] /. sol, {t, 0, 10}]

• Thank you very much. This is exacly what I was missing! Apr 7, 2015 at 13:15