7
$\begingroup$

I have a permutation in $S_4$, Cycles[{2, 4}]. I want to produce the permutation matrix of this permutation. In other words, I want Mathematica to return the list {{1, 0, 0, 0}, {0, 0, 0, 1}, {0, 0, 1, 0}, {0, 1, 0, 0}}.

$\endgroup$
1
  • 1
    $\begingroup$ This seem the Identy Matrix with the rows 2 and 4 interchanged. Table[IdentityMatrix[4][[i]],{i,PermutationList[Cycles[{{2, 4}}], 4]}] $\endgroup$
    – vi pa
    Apr 13, 2020 at 13:26

3 Answers 3

8
$\begingroup$
n = 4
SparseArray[
 Transpose[{Range[n], PermutationList[Cycles[{{2, 4}}], n]}] -> 1,
 {n, n}
 ]
$\endgroup$
2
  • $\begingroup$ You don't even need to define n if you do SparseArray@MapIndexed[{#2[[1]], #1} -> 1 &, PermutationList[Cycles[{{2, 4}}]]]. $\endgroup$
    – Roman
    Apr 13, 2020 at 12:22
  • 1
    $\begingroup$ I know. Btw., calling SparseArray and PermutationList without a second argument is asking for trouble. And Map and friends are slow. ;) $\endgroup$ Apr 13, 2020 at 12:25
8
$\begingroup$

IdentityMatrix[4][[#]]&/@PermutationList[Cycles[{{2, 4}}], 4]

$\endgroup$
3
  • $\begingroup$ Thank you. This is very helpful. $\endgroup$
    – geoffrey
    Apr 13, 2020 at 13:57
  • 3
    $\begingroup$ IdentityMatrix[4][[PermutationList[Cycles[{{2, 4}}], 4]]] is a bit simpler. $\endgroup$
    – Roman
    Apr 13, 2020 at 13:58
  • 5
    $\begingroup$ also: Permute[IdentityMatrix[4], Cycles[{{2, 4}}]] (+1) $\endgroup$
    – kglr
    Apr 13, 2020 at 16:43
7
$\begingroup$

Starting in version 13.1, one can just evaluate

PermutationMatrix[Cycles[{{2, 4}}]] // Normal
   {{1, 0, 0, 0}, {0, 0, 0, 1}, {0, 0, 1, 0}, {0, 1, 0, 0}}

but it might be better to omit the Normal[] and keep the matrix in its structured form, since internal operations like Dot[] are optimized to work with the structured form.

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