3
$\begingroup$

I am trying to use NDSolve to solve problems involve previous time step value. For example, instead of using the working code below:

    NDSolve[{x'[t] == a[t] Sin[t], x[0] == 0, a[0] == 1, 
           WhenEvent[Sin[t] == 0, a[t] -> -a[t]]}, x, {t, 0, 20} , 
          DiscreteVariables -> {a}, StartingStepSize -> 0.1, Method -> {"FixedStep", 
  Method -> {"ExplicitRungeKutta", "DifferenceOrder" -> 4, 
    "Coefficients" -> ClassicalRK4Coefficients}}];

how i wish i could replace the WhenEvent above with

WhenEvent[x[t]-x[t-0.1] < 0, a[t] -> -a[t]]

(to note x[t] is current value and x[t-0.1] is previous value). I have no idea how to apply it, anyone can enlighten me?

$\endgroup$
  • $\begingroup$ Welcome to Mathematica.SE! I hope you will become a regular contributor. To get started, 1) take the introductory tour now, 2) when you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge, 3) remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign, and 4) give help too, by answering questions in your areas of expertise. $\endgroup$ – bbgodfrey Jul 11 '17 at 13:02
4
$\begingroup$

This question can be solved by storing the old value of x as an additional discrete variable.

s = Flatten@NDSolve[{x'[t] == a[t] Sin[t], x[0] == 0, a[0] == 1, tem[0] == 0, 
    WhenEvent[Mod[t, .1] == 0, {If[x[t] - tem[t] < 0, a[t] -> -a[t]], tem[t] -> x[t]}]}, 
    {x, a}, {t, 0, 20}, DiscreteVariables -> {a, tem}, StartingStepSize -> 0.1, 
  Method -> {"FixedStep", Method -> {"ExplicitRungeKutta", "DifferenceOrder" -> 4}}];

Plot[x[t] /. s, {t, 0, 20}, AxesLabel -> {t, x}]

enter image description here

Plot[a[t] /. s, {t, 0, 20}, AxesLabel -> {t, a}]

enter image description here

Note that this method works equally well for non-constant time-steps.

$\endgroup$
  • $\begingroup$ Thank you very much. You helped me a lot. I appreciated it. $\endgroup$ – VTeh Jul 11 '17 at 13:53

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.