1
$\begingroup$

(A very simplified version of my code:)

How can I create a Table[] with a variable number of dimensions, e.g.:

Table[foo,{i1,3},{i2,3},...,{iN,3}]

where N is an argument sent into a Module[]?

I have tried many things, including Sequence[] to try to rid of outermost braces (of the sort-of List[] after foo) -- nada.

Thank you.

$\endgroup$
  • $\begingroup$ Please edit the post and include one of the many things you have tried. $\endgroup$ – Edmund Jul 26 '17 at 0:22
1
$\begingroup$
table[m_, n_] := Module[{dims = ConstantArray[m , n]}, Array[foo, dims]]

table[2, 4] // MatrixForm /@ # & // MatrixForm

enter image description here

table[3, 3] // MatrixForm /@ # & // MatrixForm

enter image description here

$\endgroup$
  • $\begingroup$ I had forgotten about Array[] -- thanx. But I needed a fancier set of values for the indices. $\endgroup$ – Aharon Naiman Aug 9 '17 at 13:30
1
$\begingroup$

You have to use Evaluate at the right point, and may use indices like i[n]. For example:

With[{dim = 4, level = 3},
 Flatten[
    Table[i[1], Evaluate[Sequence@@Table[{i[n], level}, {n, dim}]]],
    dim - 1
  ]
]
(* {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \
1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, \
2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, \
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3} *)

The i[1] argument is just an example. You can access any index i[k] in this expression. Another example is

With[{dim = 3, level = 2},
  Flatten[
    Table[f[i[2], i[3]]^i[1], Evaluate[Sequence@@Table[{i[n], level}, {n, dim}]]],
    dim - 1
  ]
]
(* {f[1, 1], f[1, 2], f[2, 1], f[2, 2], f[1, 1]^2, f[1, 2]^2, f[2, 1]^2, 
    f[2, 2]^2} *)
$\endgroup$
  • $\begingroup$ This is just what I needed. I thought (and just looked again now) that I had used Evaluate[] and Sequence[] in just this order, but I guess it must have been slightly different. $\endgroup$ – Aharon Naiman Aug 9 '17 at 13:33

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.