Skip to main content
2 of 3
added 46 characters in body
Dr. belisarius
  • 116.2k
  • 13
  • 205
  • 456

Issues with creating functions

Sometimes when I try to create a function inside a function, mathematca 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 by question boils down to: Why does Code Version A work and Code Version B doesn't?