I want to perform a Do command with n variables, where n is set elsewhere in my code. How do I do that?
For example, suppose s={0,1} and n=2, then I want a code that runs
Do[Print[{var1,var2}],{var1,s},{var2,s}]
and when I set n=3, then I want a code that runs
Do[Print[{var1,var2,var3}],{var1,s},{var2,s},{var3,s}].
(Print is used just as a simple example here.) I have tried
Do[Print[ToExpression[Table["i"<>ToString[i],{i, n}]]],ToExpression[Table["{i"<>ToString[i]<>",s}",{i, 1, n}]]]
but Mathematica complains due to the result of the second ToExpression containing extra pair of curly brackets (Table produces a list). I tried removing these brackets with Row (as suggested https://community.wolfram.com/groups/-/m/t/1219718) or Delete (as suggested here Is there a function in Mathematica which removes brackets wrapping an expression?), but could not get code to work due to my limited knowledge of Mathematica.
I know I can do Tuples but that produces a large output when s is large (i.e., requires a lot of memory).
I will appreciate any comments.
Array[Total[{##}] &, {3, 4, 2}]Notice that it generalizes to $n$ dimensions without problem. Can you explain your use case in enough detail that it becomes apparent why such a solution would not be possible for you? – Szabolcs May 11 '20 at 10:56ndimensional vectors such that a) all elements are drawn froms, b) the elements sum to 1 and c) the elements are increasing. One way to do this is to generate allntuples fromsand then test each tuple for a)-c). However, this generates all tuples at ones and requires a lot of memory whensis large. – Jan May 11 '20 at 11:04Subsets, notTuples. This will improve performance significantly because you just got rid of a lot of permutations. If there are still too many subsets, you can useSubsets's 3rd argument to only generate thenth one, thus being able to iterate through them without generating all of them first. – Szabolcs May 11 '20 at 11:39Subsetsworks as suggested. Thank you. – Jan May 11 '20 at 12:00