During the execution of the following code a column of three lists and two sliders are displaying in output. The first list updates if either a or b changes. The second list updates only if the value of a is changed. Similarly, the third list updates only if the value of b is changed.
a = 0;
b = 0;
Column[
{
Dynamic[{a, b}, TrackedSymbols :> {a,b}],
Dynamic[{a, b}, TrackedSymbols :> {a}],
Dynamic[{a, b}, TrackedSymbols :> {b}],
Slider[Dynamic[a], {0, 1}],
Slider[Dynamic[b], {0, 1}]
}
]
Next I would like to replace {a,b} by a list x with two elements:
x = {0, 0};
Column[
{
Dynamic[{x[[1]], x[[2]]}, TrackedSymbols :> {x}],
Dynamic[{x[[1]], x[[2]]}, TrackedSymbols :> {x[[1]]}],
Dynamic[{x[[1]], x[[2]]}, TrackedSymbols :> {x[[2]]}],
Slider[Dynamic[x[[1]]], {0, 1}],
Slider[Dynamic[x[[2]]], {0, 1}]
}
]
It is easy to check that now only the first list updates. Please help me to solve this problem.
Answer
You can create your own list of symbols with Unique.
Clear[x];
nVars = 20;
x = Table[Unique[x], {nVars}];
vars = Map[Hold, OwnValues@x, {-1}][[-1, -1]]
(# = 0.) & /@ x;
(* {Hold[x$363], Hold[x$364], ...} *)
It's convenient to store the held variables, since once they are initialized, it's tricky to get the symbols unevaluated. We can get at the symbols via various tricks:
vars[[2]] /. Hold[var_] :> (TrackedSymbols :> {var}
(* --> TrackedSymbols :> {x$364} *)
Dynamic @@ vars[[3]]]
(* --> Dynamic[x$364] *)
Here's an example like the one in the question.
Grid[Transpose@
{Table[Dynamic[x, #] &[vars[[i]] /. Hold[var_] :> (TrackedSymbols :> {var})],
{i, Length@x}],
Table[Slider[Dynamic @@ vars[[i]]], {i, Length@x}]}
]
Here's the output for nVars = 4, where each slider has been clicked once in turn:

Comments
Post a Comment