# How do I generate all $n\times m$ matrices s.t. $a_{i,j} \in {a ... b}$?

Is there a fast and clean way of generating all possible $n\times m$ matrices s.t. $a_{i,j} \in \{a ... b\}$ - much like Range does in $N$?

Consider for example that for $n,m = 2$, $a=0$, $b=2$ I would like to have

{{{0,0},{0,0}},
{{0,0},{0,1}},
{{0,0},{0,2}},
{{0,0},{1,0}},
...
{{2,2},{2,2}}}


For the $2 \times 2$ case I got it working in the following horribly dirty way:

GenMat[a, b] :=
Partition[
Partition[
Flatten[
Table[{{x, y}, {w, z}},
{x, a, b}, {y, a, b}, {w, a, b}, {z, a, b}
]
],
2],
2];


I am however not pleased with it, not to say ashamed.

How would I best improve upon it and generalize it?

Thanks.

• Partition[#, 2] & /@ Tuples[Range[0, 2], 4] Commented Apr 8, 2015 at 18:20
• f[a_, b_, n_] := Partition[#, n] & /@ Tuples[Range[a, b], n^2] Commented Apr 8, 2015 at 18:21
• Sweet. So concise. Is by the way this exactly the same as Map[Partition[#1, n] &, Tuples[Range[a, b], n^2]]? Commented Apr 8, 2015 at 18:27

matF = Tuples[#1, {##2}] &;;


Examples:

matF[Range[0, 2], 2, 2] // Short


{{{0,0},{0,0}},{{0,0},{0,1}},<<77>>,{{2,2},{2,1}},{{2,2},{2,2}}}

MatrixForm /@ matF[Range[0, 2], 2, 2]


matF[Range[3, 5], 2, 3] // Short


{{{3,3,3},{3,3,3}},{{3,3,3},{3,3,4}},<<726>>,{{5,5,5},{5,5,5}}}

Alternatively, you can use

matF2 = Tuples[Range[#, #2], {#3, #4}] &;


matF2[a, b, c, d] gives the same output as matF[Range[a, b], c, d].