# How to make Mathematica re-evaluate a cell after some event?

I am doing a little project to demonstrate something:

a = 2; b = 5000;
d = 10000; l1 = {};
rc := RandomChoice[{a, b} -> {0, 1}]
c = 1; While[c <= d, AppendTo[l1, rc];c++]
e = ((Count[l1, _] - Count[l1, 0])/d)*100//N
f = 100 - e


I want to insert two InputFields for the values of A and B, but I want it to re-evaluate the rest of the cell whenever I input new values for A and B - I'm also curious for A or B.

Note - Inserting the inputfields is not my problem, my problems is only the reevaluation of the cell after some event.

• Are you looking for Dynamic? – Szabolcs Mar 2 '12 at 10:48
• @Szalbocs Kinda. – Billy Rubina Mar 2 '12 at 16:44

The simplest solution IMHO is using Manipulate. Almost no change in your code is necessary:

Manipulate[
d = 10000; l1 = {};
rc := RandomChoice[{a, b} -> {0, 1}];
c = 1; While[c <= d, AppendTo[l1, rc]; c++];
Column[
{
e = ((Count[l1, _] - Count[l1, 0])/d)*100 // N,
f = 100 - e
}
],
{a, 2}, {b, 5000},
TrackedSymbols -> {a, b}
] • It is indeed the simplest! I think I have to relearn Manipulate before overcomplicating things. – István Zachar Mar 2 '12 at 14:05
• @IstvánZachar, so do I. It is an area of Mathematica I am not familiar with. – rcollyer Mar 2 '12 at 14:53
• Nice, didn't know i could apply Manipulate that way. – Billy Rubina Mar 2 '12 at 16:53
• @Sjoerd There's a problem here: It keeps evaluating ad infinitum, I want it to evaluate only when the values of a or b are changed. – Billy Rubina Mar 2 '12 at 19:34
• @GustavoBandeira Did you include the TrackedSymbols -> {a, b} line specifically entered here to prevent that and are your a and b in lowercase (and not uppercase as in the text of your question)? – Sjoerd C. de Vries Mar 2 '12 at 22:02

Using DynamicModule (note that I modified some of your default values to give a more intuitive output):

   DynamicModule[{a = 2, b = 5, d = 30, update, e, f, temp = 1, rc, l1},

Grid[{
{"weight of 0 (a)", InputField[Dynamic[a, (a = #; update[]) &]]},
{"weight of 1 (b)", InputField[Dynamic[b, (b = #; update[]) &]]},
{"random choice from (0, 1) (rc)", Dynamic@rc},
{"list (l1)", Dynamic@l1},
{"e", Dynamic@e},
{"f", Dynamic@f}
}, Alignment -> {{Right, Left}}],

Initialization :> (
update[] := Module[{c = 1},
l1 = {};
rc = RandomChoice[{a, b} -> {0, 1}];
While[c <= d, AppendTo[l1, rc]; c++];
e = ((Count[l1, _] - Count[l1, 0])/d)*100 // N;
f = 100 - e;
temp++;
];
update[]
)] • Your method is also nice. It has some functions i've never seen. I'll explore them too. – Billy Rubina Mar 2 '12 at 18:16