3
$\begingroup$

Is there any function to directly create a flat list of expressions as a function of multiple index variables, in other words a flat version of Table. What I mean is to have for example

flatTable[expr[a,b],{a,1,3},{b,7,8}] 

output a list

{expr[1,7],expr[1,8],expr[2,7],expr[2,8],expr[3,7],expr[3,8]}

(or perhaps in a different order). Note that expr[i,j] could be a List (or a list of lists etc).

One solution seems to be:

flatTable[expr_,indices__]:=Flatten[#,{Range[Length[{indices}]]}]&@Table[expr,indices] 

but there must be a better way.

$\endgroup$
  • 3
    $\begingroup$ Look at Tuples. For instance, expr @@@ Tuples[{{1, 2, 3}, {7, 8}}]. $\endgroup$ – MarcoB Jun 13 '18 at 12:52
  • $\begingroup$ flatTable = Join @@ Table[##] &? $\endgroup$ – kglr Jun 13 '18 at 13:07
  • $\begingroup$ Probably the shortest version: Flatten@*Table $\endgroup$ – Wjx Jun 13 '18 at 14:46
  • $\begingroup$ @Wjx, what did you mean with the star? (If you meant Flatten@Table then it of course does not work if the expression in the table already has a list structure.) $\endgroup$ – Kvothe Jun 13 '18 at 16:20
  • $\begingroup$ @Kvothe that is Composition ~ which is almost identical to Flatten[Table[##]]& $\endgroup$ – Wjx Jun 14 '18 at 10:48
3
$\begingroup$
ClearAll[flatTable]
flatTable = Flatten[Table@##, Length[{##2}] - 1] &;

Examples:

flatTable[expr[a, b], {a, 1, 3}, {b, 7, 8}]

{expr[1, 7], expr[1, 8], expr[2, 7], expr[2, 8], expr[3, 7], expr[3, 8]}

flatTable[expr[a, b, c], {a, 1, 3}, {b, 7, 8}, {c, 5, 6}]

{expr[1, 7, 5], expr[1, 7, 6], expr[1, 8, 5], expr[1, 8, 6], expr[2, 7, 5], expr[2, 7, 6], expr[2, 8, 5], expr[2, 8, 6], expr[3, 7, 5], expr[3, 7, 6], expr[3, 8, 5], expr[3, 8, 6]}

| improve this answer | |
$\endgroup$
  • $\begingroup$ thanks. This is basically in the spirit of the solution I included myself. But it is a good lesson to see how I could have written it slightly cleaner / more compact. $\endgroup$ – Kvothe Jun 13 '18 at 13:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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