Is is possible to use NDSolve with DiscreteVariables if there are no continuous-time variables?

This fails:

NDSolve[{x[0] == 1,
    WhenEvent[Mod[t, 1] == 0, x[t] -> -x[t]]}, {x}, {t, 0, 7}, 
    DiscreteVariables -> {x}]

It works if I remove the DiscreteVariables, replacing it with $x'(t)=0$:

NDSolveValue[{x[0] == 1, x'[t] == 0,
    WhenEvent[Mod[t, 1] == 0, x[t] -> -x[t]]}, {x}, {t, 0, 7}]

(This seems to defeat the purpose of DiscreteVariables.)

It works if I introduce a "dummy" continuous-time variable:

NDSolveValue[{y'[t] == 0, y[0] == 0, x[0] == 1, 
    WhenEvent[Mod[t, 1] == 0, x[t] -> -x[t]]}, {x, y}, {t, 0, 7}, 
    DiscreteVariables -> {x}]

(This seems like a hack.)

I ask because I have a system of equations

$$x_i(T_i^{k+1})=\sum_{j=1}^N a_{i,j} x_j(T_i^k), \quad i=1,\ldots,N$$

where each variable $x_i(t)$ changes only at the discrete times $\{T_i^k\}_{k \in \mathbb{N}}$.


  • 2
    $\begingroup$ I often use the dummy-variable "hack" to drive DAEs. -- Might be considered a design flaw, or one might think the D in NDSolve should mean something. :) $\endgroup$
    – Michael E2
    Commented May 18, 2016 at 0:40
  • 1
    $\begingroup$ I see what you mean, but if NDSolve isn't the right tool for this, is there a more appropriate function I'm overlooking? $\endgroup$ Commented May 18, 2016 at 3:52
  • $\begingroup$ I think it's the best available tool, even if it's not the best imaginable tool. NDSolve is the only built-in way to construct a discontinuous InterpolatingFunction (see here for a manual method). If if one knows ahead of time the times that the variable changes, one could directly construct a Piecewise function (see here or here).... $\endgroup$
    – Michael E2
    Commented May 18, 2016 at 12:07
  • $\begingroup$ ...I view your problem as an "differential-order-0" form of "integration" (in the sense of putting together a function). FunctionInterpolation takes a global approach like NIntegrate. NDSolve takes a local approach, but primarily for order > 0; however, via DAEs, it can simultaneously do order-0 integrations. I don't think there's an analog of FunctionInterpolation. $\endgroup$
    – Michael E2
    Commented May 18, 2016 at 12:07
  • $\begingroup$ I see. Thank you @MichaelE2 ! $\endgroup$ Commented May 18, 2016 at 13:35


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.