2
$\begingroup$

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.

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

1 Answer 1

6
$\begingroup$
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]

enter image description here

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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