Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 1 down vote accepted

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.

share|improve this answer

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

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.

share|improve this answer
I think Outer[List, Sequence @@ ConstantArray[Range[-m, m], n]] is better. – ybeltukov Sep 28 '13 at 23:46

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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