4
$\begingroup$

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

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

2 Answers 2

6
$\begingroup$

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.

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

Using integer manipulations only:

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

enter image description here


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

$\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.