I have a self-defined function which is fairly complicated and gives the analytical form. The result contains two independent variables. I use Animate to plot the function by enumerating one parameter.

myfun[x_, y_] := ... (* here are some complicate calculation *)
Animate[Plot[myfun[x, y], {x, 0, 2.5}], {y, 0, 5.0, 0.5}]

Each plot in the Animate will call myfun each time it needs a value from it, that's why the animation runs slowly. I don't know how to speed up code. But now, I run myfun once, copy the resulting expression and paste it to make a new function

myfun[x_, y_] := ... (* here are some complicate calculation *)
(* here it returns some expression and I copy and paste it into myfun2 *) 
myfun2[x1_, y1_] := EXPRESSION_FROM_PASTE /. {x -> x1, y -> y1}
Animate[Plot[myfun2[x, y], {x, 0, 2.5}], {y, 0, 5.0, 0.5}]

It runs pretty fast now. But if I change some parameter or math in myfun, I need to copy and paste the function again to make myfun2. Is that anyway to achieve that programatically? Thanks.

  • 4
    $\begingroup$ Search this site for "memoization", specially Leonid's answers $\endgroup$ Sep 30, 2013 at 2:14

1 Answer 1


This answer has nothing to do with memorization as mentioned by @belisarius in the comment. I'm not sure what kind of complicated calculation you have in myfun, but if you expect to get a more concise/simpler expression from myfun and then assign it to myfun2 for further manipulation, a slightly better way to go without manually copy and paste is

myfun[x_, y_] := ... (* here is your complicated calculation *)
myfun2[x1_, y1_] := Evaluate[myfun[x, y]/.{x->x1, y->y1}//Simplify]

or even a simpler one (just one-line)

myfun3[x_, y_] := Evaluate[...(* here is your complicated calculation in myfun *)//Simplify] 

which forces the right hand side to be evaluated first and then be assigned to myfun3. Note that I assume Simplify could somehow simplify the analytical expression obtained from the calculation. Given the description of your text, I assume this answers more or less your question?

  • $\begingroup$ Thanks Fang. Yes, Evaluate is really what I am looking for $\endgroup$ Oct 2, 2013 at 3:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.