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 -> Trueto your second Plot – Dr. belisarius Oct 04 '13 at 18:52bugstag 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. – Szabolcs Oct 04 '13 at 19:07Evaluatedis 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}}– Rolf Mertig Oct 04 '13 at 20:56HoldAll, which is hard to explain. – Rolf Mertig Oct 04 '13 at 20:57