# Generate higher dimensional box vectors

I'd like to generate integer vectors in $\{-M,-M+1,\dots,M\}^n$, where $M$ and $n$ are parameters. For a fixed $n$, say $n=3$ for instance, I only know I can use

Flatten[Table[{i, j, k}, {i, -M, M}, {j, -M, M}, {k, -M, M}]]


to get the list. But for larger $n$, I would have to add more coordinate ranges manually. Is there an automatic way to do this?

I have a similar question on Sum and NSum; for instance, I want to compute $\sum_x e^{-\|x\|^2}$ for $x$ over $\{-M,\dots,M\}^n$. For $n=3$ I could write

NSum[E^(-(i^2 + j^2 + z^2)), {i, -M, M}, {j, -M, M}, {k, -M, M}]


Is there a more automatic way to do this?

t = Tuples[Range[-m,m], n] will give you the list of n-tuples.
Then s = Total[Exp[-#.#]& /@ t] is one way to get the sum.

EDIT: There are several faster ways to get the sum. If all you want t for is to get s then it's faster to go directly to s = Total@Exp[-Total[Tuples[Range[-m,m]^2, n], {2}]], omitting t. If you want just a number, as opposed to its symbolic representation in terms of powers of E, use N@Range instead of Range.

Here's one way to go about this kind of thing:

m=3;
Outer[List, #, #, #] & @ Range[-m, m]


This gives the same thing as the Table command, which you can Flatten if desired. To add new dimensions, just increase the number of #'s, for instance:

Outer[List, #, #, #, #, #] & @ Range[-m, m]


As ybeltukov suggests, this can be made more general using Sequence

Outer[List, Sequence @@ ConstantArray[Range[-m, m], n]]


where now n is the number of required dimensions. Or one could do

Outer[List, Sequence @@ ConstantArray[#, 3]] & @ Range[-m,m]


which uses ConstantArray to generate all the #'s and Sequence to splice them into the function.

• I think Outer[List, Sequence @@ ConstantArray[Range[-m, m], n]] is better. Sep 28, 2013 at 23:46