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}}
.
3 Answers
$\begingroup$
$\endgroup$
2
n = 4
SparseArray[
Transpose[{Range[n], PermutationList[Cycles[{{2, 4}}], n]}] -> 1,
{n, n}
]
-
$\begingroup$ You don't even need to define
n
if you doSparseArray@MapIndexed[{#2[[1]], #1} -> 1 &, PermutationList[Cycles[{{2, 4}}]]]
. $\endgroup$– RomanCommented Apr 13, 2020 at 12:22 -
1$\begingroup$ I know. Btw., calling
SparseArray
andPermutationList
without a second argument is asking for trouble. AndMap
and friends are slow. ;) $\endgroup$ Commented Apr 13, 2020 at 12:25
$\begingroup$
$\endgroup$
3
IdentityMatrix[4][[#]]&/@PermutationList[Cycles[{{2, 4}}], 4]
-
$\begingroup$ Thank you. This is very helpful. $\endgroup$– geoffreyCommented Apr 13, 2020 at 13:57
-
3$\begingroup$
IdentityMatrix[4][[PermutationList[Cycles[{{2, 4}}], 4]]]
is a bit simpler. $\endgroup$– RomanCommented Apr 13, 2020 at 13:58 -
5$\begingroup$ also:
Permute[IdentityMatrix[4], Cycles[{{2, 4}}]]
(+1) $\endgroup$– kglrCommented Apr 13, 2020 at 16:43
$\begingroup$
$\endgroup$
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.
Table[IdentityMatrix[4][[i]],{i,PermutationList[Cycles[{{2, 4}}], 4]}]
$\endgroup$