Given a certain number n, I want to define n controls within Manipulate with the correct variable labelling. Visually, I want something like

enter image description here

where, for example, the output panel is the sum of ci's ($1\leq$i$\leq $n), that is, 1 if the checkbox is ticked and 0 otherwise.

Using Dynamic and Table I can get close to my goal with the following code

Manipulate[Sum[c1, {i, n}],
 Control[{{n, 1}, 1, 10, 1, Appearance -> "Labeled"}],
 Dynamic[Table[Control[{{c1, 0}, {1, 0}}], {i, n}] // Column]]

enter image description here

It becomes then a question of defining the variables within the Table and Control environment. I'm aware of this question, but unfortunately using Symbol or ToExpression within Control didn't seem to work.

I'm ultimately asking two questions:

  1. How do I correctly introduce and relabel new variables depending on n, that is, c1, c2, ... , cn? Maybe using c[i] instead?
  2. If I manage the first, how can I then easily manage such variables for a given output function? For example, if I want to sum them, Sum[ci,{i,n}] wouldn't work, so I might need something like c[i] or Symbol["c"<>ToString@i].

Any ideas?

PS - This is a follow-up question to this question. I realised this was trickier than I initially thought and decided to ask a question solely focused on variable definition.


1 Answer 1

Manipulate[Sum[cs[[i]], {i, n}],
 {{cs, ConstantArray[0, 10]}, ControlType -> None}, 
 {{n, 1, "n"}, 1, 10, 1, Appearance -> "Labeled"}, 
 Dynamic[Grid[Table[With[{i = i},
      {Symbol["c" <> ToString[i]], Checkbox[Dynamic[cs[[i]]], {0, 1}]}], 
      {i, n}]]]]

enter image description here

  • $\begingroup$ Short and elegant. Thank you! $\endgroup$
    – sam wolfe
    Mar 3, 2020 at 14:25

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.