2
$\begingroup$

I am trying to solve a differential equation that changes its behaviour depending on the value of the dependent variable. I've tried as shown below, but the computer does not understand my If clause as an "equation or set of equations".

NDSolve[{If[x[t] > 0, x''[t] == -x[t], x''[t] == -2*x[t]], x[0] == 1,      
x'[0] == 0}, x, {t, 0, 10}]

How can I make this work?

$\endgroup$
1
  • 1
    $\begingroup$ You can surely use WhenEvent[] as @anders describes, but otherwise, your If[] is not properly structured: NDSolve[{x''[t] == If[x[t] > 0, -x[t], -2 x[t]], x[0] == 1, x'[0] == 0}, x, {t, 0, 10}] $\endgroup$ Commented Feb 3, 2020 at 15:30

1 Answer 1

2
$\begingroup$

You can use WhenEvent (note the use of DiscreteVariables):

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

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

enter image description here

$\endgroup$

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.