Sometimes when I try to create a function inside a function, mathematcaMathematica 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/why certain things work and others don't. Here's an example I just ran into recently:
CODE VERSION A: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]ans[2]
inside my function by replacing it with the %%
, Mathematica can't evaluate it!
CODE VERSION B: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 bymy question boils down to: WhyWhy does Code Version A work and Code Version B doesn't?