# variable dimension table

(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.

• Please edit the post and include one of the many things you have tried. Commented Jul 26, 2017 at 0:22

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} *)

• 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. Commented Aug 9, 2017 at 13:33
table[m_, n_] := Module[{dims = ConstantArray[m , n]}, Array[foo, dims]]

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


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


• I had forgotten about Array[] -- thanx. But I needed a fancier set of values for the indices. Commented Aug 9, 2017 at 13:30