Sometimes when I try to create a function inside a function, Mathematica gives me a hard time. I usually just have to play around with the syntax until it gets something it "likes" but I really have idea why certain things work and others don't. Here's an example I just ran into recently:
Code version A:
ans[tf_] :=
NDSolve[{x'[t] == v[t], v'[t] == -x[t] - v[t], x[0] == 1,
v[0] == 1}, {x[t], v[t]}, {t, 0, tf}] // Flatten;
ans[2]
Plot[{x[t], v[t]} /. %, {t, 0, 2}]
So this works beautifully. But for some reason if I try to nest my ans[2]
inside my function by replacing it with the %
, Mathematica can't evaluate it!
Code version B:
ans[tf_] :=
NDSolve[{x'[t] == v[t], v'[t] == -x[t] - v[t], x[0] == 1,
v[0] == 1}, {x[t], v[t]}, {t, 0, tf}] // Flatten;
Plot[{x[t], v[t]} /. ans[2], {t, 0, 2}]
So my question boils down to: Why does Code Version A work and Code Version B doesn't?
Evaluated -> True
to your second Plot $\endgroup$bugs
tag for new question. We use this tag to categorize confirmed bugs. It'll be re-added if this is confirmed to be a bug by the community. $\endgroup$Evaluated
is not documented anywhere. Either, politically correct:Plot[Evaluate[{x[t], v[t]} /. %], {t, 0, 2}]
, or, faster:Plot @@ {{x[t], v[t]} /. %, {t, 0, 2}}
$\endgroup$HoldAll
, which is hard to explain. $\endgroup$