Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Suppose I need to create sliders associated with variables from a given list:

ClearAll[a, b, c, d];
vars = {a, b, c, d};
Slider[Dynamic@#, {0, 1}] & /@ vars
Dynamic@vars

Unfortunately it works only for variables which don't have values:

ClearAll[a, b, c, d];
vars = {a, b, c, d};
a = 1;
Slider[Dynamic@#, {0, 1}] & /@ vars
Dynamic@vars

As you can see now the first slider is not working because Mma attempts to assign values to raw object 1 instead of a. Nevertheless simple

Slider[Dynamic@a, {0, 1}]
Dynamic@a

produces the desired result.

So, what is the right way to do such things?

share|improve this question
add comment

1 Answer

up vote 8 down vote accepted

The best way may be to avoid such constructs, but, if you insist on using a list of variables like that, here is one way:

Thread[Hold[vars] /. OwnValues[vars]] /. Hold[v_] :> Slider[Dynamic[v], {0, 1}]

You can store variables wrapped in Hold rather than List, in which case the first step (involving OwnValues) can be skipped.

share|improve this answer
    
@Leonid, thank you. Could you explain what's wrong with this construct? –  faleichik Apr 23 '12 at 18:59
    
@Rojo I actually think that one just should find other ways to achieve the desired result (avoid solving this problem altogether). Storing variables in a list and then looking for ways to avoid evaluation seems like an unnecessary extra work to me. –  Leonid Shifrin Apr 23 '12 at 18:59
    
@faleichik Well, see my comment above. If you have several (many) variables, perhaps it is better to define a list (array) and index it to access individual variables, or use indexed variables. Having a separate variable to store a list of named variables which can evaluate, seems more complex and error-prone to me. –  Leonid Shifrin Apr 23 '12 at 19:01
    
Ok, I have to agree with you. Anyway using variable names instead of indices is sometimes more convenient for quick sketches. As you've said, using Hold instead of List is a good alternative. –  faleichik Apr 23 '12 at 19:16
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.