# Generating all possible 2x2 matrices with unique elements from 1 to 4

If I have a set A={1,2,3,4}, how do I generate all 2x2 matrices with different elements chosen from A?

It will be 4!=24 matrices like {{1,2},{3,4}}, {{1,2},{4,3}} and {{1,3},{2,4}} ...

• What about: Partition[#, 2] & /@ Permutations[{1, 2, 3, 4}] Jan 27, 2023 at 20:02
• ArrayReshape[#, {2, 2}] & /@ Permutations[{1, 2, 3, 4}]
– Syed
Jan 28, 2023 at 7:30
• Why is everyone posting solutions in the comments? Jan 28, 2023 at 7:55

Annotating my comment. The expression Permutations[{1, 2, 3, 4}] generates all 24 permutations of the list {1,2,3,4}. For example, the list {3,1,4,2} is one of those.

In order to construct a 2x2 matrix from {3,1,4,2} one needs to partition the list into a matrix. This can be done by Partition[{3,1,4,2},2]. So why the funny Partition[#, 2] & /@ Permutations[{1, 2, 3, 4}]?

Well, the Permutations[{1, 2, 3, 4}] returns a List-of- List of all permutations; also called a nested list. A nested list has a double set of {{ }}, such as {{1, 2, 3, 4}, {1, 2, 4, 3}, ..., {4, 3, 2, 1}}. And each of the sublists has to be partitioned.

The syntax for /@ is a Map, which maps the Partition[#, 2] & onto each of the sublists to create a 2x2 matrix. The # and & are essential parts of the Mathematica syntax.

So we end up with a double nested list {{{1, 2}, {3, 4}}, {{1, 2}, {4, 3}}, ..., , {{4, 3}, {2, 1}}}. I hope this helps.

• Or directly (without Map): ArrayReshape[Permutations[{1, 2, 3, 4}], {24, 2, 2}] Jan 28, 2023 at 18:54

Using integer manipulations only:

(res = Map[IntegerDigits,
QuotientRemainder[#,
100] &@(FromDigits /@ (Select[ContainsExactly[{1, 2, 3, 4}]]
[IntegerDigits /@ Range[1234, 4321]]))
, {2}]) // MatrixForm /@ # & // Multicolumn[#, 4] &


OR

(res2 = Select[ContainsExactly[{1, 2, 3, 4}]][
Tuples[{1, 2, 3, 4}, 4]] /. {a_, b_, c_,
d_} -> {{a, b}, {c, d}}) // MatrixForm /@ # & //
Multicolumn[#, 4] &