2
$\begingroup$

I would have thought that the following code would let each indexed variable take its value from the SetterBar. Instead, all the SetterBars take the same value, as the image illustrates. Essentially all the SetterBars set the value of var[j] instead of each setting the value of variables var[1], var[2], etc. How can I get Mathematica to evaluate the indices when assigning values using the SetterBars inside the Table?

TableForm[
 Table[{"Variable " <> ToString[var[j]], 
   SetterBar[
    Dynamic@var[j], {0 -> "negative", 1 -> "positive", 
     2 -> "ignore"}]}, {j, 5}]]

enter image description here

$\endgroup$

1 Answer 1

4
$\begingroup$

It's a scoping issue. You can use With to get the expected behavior.

Column[{
  TableForm[
   Table[With[{j = j}, {"Variable " <> ToString[var[j]], 
      SetterBar[Dynamic@var[j], {0 -> "negative", 1 -> "positive", 2 -> "ignore"}]}], 
    {j, 5}]],
  Table[With[{j = j}, Dynamic@var[j]], {j, 5}]}
 ]

Out

$\endgroup$
6
  • $\begingroup$ Fabulous, many thanks. Could you please explain Ma's scoping principles? Is there a logic of which commands prevent the evaluation of their contents and which do not? $\endgroup$
    – Nicholas G
    Commented Apr 1, 2017 at 23:31
  • $\begingroup$ @NicholasG "Table effectively uses Block to localize values or variables." [Table] $\endgroup$
    – Karsten7
    Commented Apr 1, 2017 at 23:36
  • $\begingroup$ @NicholasG Scoping Constructs $\endgroup$
    – Karsten7
    Commented Apr 1, 2017 at 23:37
  • $\begingroup$ Why does the variable name get substituted by its value when I reevaluate this? TableForm[ Table[{"Variable " <> ToString[var[j]], With[{j = j}, SetterBar[ Dynamic@var[j], {0 -> "liberal", 1 -> "conservative", 2 -> "ignore"}]]}, {j, 5}]] $\endgroup$
    – Nicholas G
    Commented Apr 1, 2017 at 23:51
  • 1
    $\begingroup$ @NicholasG Or use ToString[Unevaluated@var[j]] instead. $\endgroup$
    – Karsten7
    Commented Apr 1, 2017 at 23:55

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.