# Constructing a permutation matrix

**URL:** <https://discourse.julialang.org/t/constructing-a-permutation-matrix/129234>\
**Category:** General Usage\
**Tags:** linearalgebra\
**Created:** [May 21, 2025, 11:04pm UTC](https://discourse.julialang.org/t/constructing-a-permutation-matrix/129234 "2025-05-21T23:04:23Z")\
**Posts on this page:** 1\
**Showing post:** 9

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [May 22, 2025, 6:37pm UTC](https://discourse.julialang.org/t/constructing-a-permutation-matrix/129234/9 "2025-05-22T18:37:16Z")

</div>

> [@mikmoore](#):
>
> Although the permutation should be inverse-applied (i.e., with its transpose) on one side or the other if it’s actually to be treated as a permutation matrix, which would make this a bit more complicated.

Yes, the `getindex` should be

```julia
Base.getindex(P::PermutationMatrix, i::Integer, j::Integer) = P.p[i] == j

```

and the right-multiplication should be:

```julia
function Base.:*(A::AbstractMatrix, P::PermutationMatrix)
    AP = similar(A)
    AP[:, P.p] = A # computes AP = (PᵀAᵀ)ᵀ = (P⁻¹Aᵀ)ᵀ
    return AP
end

```

(The test permutation `P = PermutationMatrix([2, 1, 4, 3])` happens to be symmetric, which hides these bugs. Try e.g. `PermutationMatrix([2, 4, 3, 1])` instead.)

If you wanted to be fancy, you could define all sorts of specialized routines, most obviously for `inv(P)` and `P \ x` (`ldiv!`), but also for things like eigenvectors and eigenvalues (which can be computed from the cycles of the permutation, and moreover you can then multiply by the eigenvectors using FFTs, giving you fast algorithms for things like matrix exponentials and logarithms of permutations etcetera), and more.

It’s a fair amount of work to get something truly full-featured, but it might be fun for someone. Still I’m not sure of the practical motivation.

---

_[View the full topic](https://discourse.julialang.org/t/constructing-a-permutation-matrix/129234)._
