# Why does Manipulate execute the expression twice?

When I execute Foobar[] in the code below and move a slider, the variable grad is printed twice. Why is this? How can I make the Manipulate body only execute once on each update?

Foobar[] := Module[{f, vars, grad},
f = a x^3 - b x^2 + c y^2;
vars = {a, b, c};
With[{fman = f, controls = Apply[Sequence, {{#, 0}, -5, 5} & /@ vars]},
Manipulate[
g = fman/(x^2 + y^2 + 1);
grad = D[g, {{x, y}}];
, controls]
]
];


Edit: As noticed below, this function is creating a Manipulate. My concern is why the Manipulate appears to be executing twice for every one update. This is a minimal working example and hence there is significant amount of code (that takes a while to run) excluded from inside the Manipulate body. I included Print to emphasize that the code appears to be executing twice.

• you should put everything inside manipulate, like it is supposed to be. do not invent strange constructs and wonder why and what. waste of time to analyze as it is not the right way to do something. Jul 16, 2012 at 19:10
• @RobertH It looks like he's writing a function that will create a Manipulate. There's nothing wrong with that. I would expect that eventually f and vars will be passed in as arguments of Foobar. Jul 16, 2012 at 19:22
• By the way, this answer should help you: mathematica.stackexchange.com/a/8073/69 Jul 16, 2012 at 19:24

I think what you need is ContinuousAction -> False and TrackedSymbols -> vars:

Foobar[] :=
Module[{f, vars, grad}, f = a x^3 - b x^2 + c y^2;
vars = {a, b, c};
With[{fman = f, controls = Apply[Sequence, {{#, 0}, -5, 5} & /@ vars]},
Manipulate[
g = fman/(x^2 + y^2 + 1);
grad = D[g, {{x, y}}];

ContinuousAction -> False is needed to keep from evaluating continuously while dragging the sliders. In the original version this happened and the Print statements were sent to the Messages window.
TrackedSymbols -> vars is needed to keep Mathematica from reevaluating when the values of g or grad change (which would be necessary if these were interdependent).
• Interesting, this does seem to fix it. Why do you think a Rule is necessary for TrackedSymbols rather than a RuleDelayed? Jul 16, 2012 at 20:21
• @James presumably Manipulate checks to see that the value of TrackedSymbols is a list of Symbols, and vars is not expressly so. If this is of considerable interest to you post it as a new question and I will dig deeper. Jul 16, 2012 at 20:25