mgolunski
mgolunski

Reputation: 45

Mathematica - List of initialized variables

I want to make a list of variables that would be initialized and accessible.
After that kind of code:

abc = {a, b, c}
{a, b, c} = {0, 0, 0}
abc[[1]] = 1

In other way I'd like create a list of variables, initialize them with zeroes and then change them by referring to the variable indicating list rather then using individual variables' names.

If you would do

abc = {a, b, c}
Evaluate[abc[[1]]] = 1

you get the right thing, i.e. variable a is set to 1. But after first set you can't set another value to that variable using the method above.

More details
I want to create list of SetterBars where each one is independent of others and I can somehow store their values. What's more I want them to be initialized as zeroes. Something like

abc = {a, b, c};
Evaluate[abc] = {0, 0, 0};
Table[SetterBar[Dynamic[ abc[[i]] ],{-1,1}], {i,3}]

Upvotes: 3

Views: 1149

Answers (2)

Mr.Wizard
Mr.Wizard

Reputation: 24336

Solution

The simple answer is to use indexed objects rather than symbols:

x[_] = 0;

Array[SetterBar[Dynamic @ x @ #, {0, 1}] &, 3] // Row

Array[Dynamic @ x @ # &, 3]

Mathematica graphics

You are not limited to user numeric indexes. For example:

SetterBar[Dynamic @ x @ #, {0, 1}] & /@ {"one", "two", "three"}

Dynamic @ x @ # & /@ {"one", "two", "three"}

References

See: Wrapping EventHandler by Table for a more complete example and other options.

For a method to perform the Symbol assignment you describe, even though I do not recommend it here, see: Assigning values to a list of variable names, as well as: (1), (2), (3), (4)

Upvotes: 1

Rolf Mertig
Rolf Mertig

Reputation: 1362

I am sure this can be simplified, but at least it does work:

     {a, b, c} = {0, 1, 0}; 
        {
          With[{abc = {Unevaluated[a], Unevaluated[b], Unevaluated[c]}}, 
               tab = Table[With[{abci = abc[[i]]}, 
                                SetterBar[Dynamic[abci], {0, 1}]], {i, 3}]; 
               tab /. Dynamic[Unevaluated[x_]] :> Dynamic[x]
          ], 
         Dynamic[{a, b, c}]
        }

Upvotes: 1

Related Questions