First time posting.
Reproducing the Problem
I'm relatively new to Mathematica (using v.12.3), and working on a project. My problem can be reproduced with this.
m[x_] := {{x, 0}, {0, x}} f[x_] := Piecewise[{{m[x], x <= 5}}, m[1]] test = NDSolve[{y'[t] == f[t][[1, 1]], y[0] == 0}, y, {t, 0, 10}] Outside of NDSolve, f[t][[1,1]] evaluates as expected using the Piecewise function (i.e., f[3][[1,1]] = m[3][[1,1]] but f[10][[1,1]] = m[1][[1,1]]).
However, NDSolve does not seem to evaluate the Piecewise function before attempting to use it, as the stack trace gives:
NDSolve[{Derivative[1][y][t] == {{{t, 0}, {0, t}}, t <= 5}, y[0] == 0}, y, {t, 0, 10}] Attempted Solutions & Workarounds
Moving the Piecewise statement within NDSolve seems to produce the expected result.
m[x_] := {{x, 0}, {0, x}} f[x_] := m[x] test = NDSolve[{ y'[t] == Piecewise[{{f[t][[1, 1]], t <= 5}}, m[1][[1, 1]]], y[0] == 0}, y, {t, 0, 10}] I also tried If statements:
m[x_] := {{x, 0}, {0, x}} f[x_] := If[x >= 10, m[x], m[1]] test = NDSolve[{y'[t] == f[t][[1, 1]], y[0] == 0}, y, {t, 0, 10}] However, this appears to ignore the If statement entirely when comparing the outputs using Plot[y[t] /. test, {t, 0, 10}].
I have looked around extensively on StackExchange and the documentation for solutions, but haven't come up with much besides a suspicion that it's
- something to do with a Hold or Delay property that I don't know about, and/or
- something to do with syntax I don't know about, and/or
- something to do with how NDSolve works?
I would appreciate an explanation for why this behavior occurs (or something I can look up to find that information myself; maybe I don't know what to look for), as I've been struggling for some 8+ hours on this. Thank you!
Edit: All excellent responses; thank you so much!



