|
| 1 | +# transpose linear indices of the square n×n matrix |
| 2 | +# i.e. |
| 3 | +# 1 4 |
| 4 | +# 2 5 => 1 2 3 |
| 5 | +# 3 6 4 5 6 |
| 6 | +transpose_linear_indices(n::Integer, m::Integer = n) = |
| 7 | + repeat(1:n, inner = m) .+ repeat((0:(m-1)) * n, outer = n) |
| 8 | + |
| 9 | +""" |
| 10 | + CommutationMatrix(n::Integer) <: AbstractMatrix{Int} |
| 11 | +
|
| 12 | +A *commutation matrix* *C* is a n²×n² matrix of 0s and 1s. |
| 13 | +If *vec(A)* is a vectorized form of a n×n matrix *A*, |
| 14 | +then ``C * vec(A) = vec(Aᵀ)``. |
| 15 | +""" |
| 16 | +struct CommutationMatrix <: AbstractMatrix{Int} |
| 17 | + n::Int |
| 18 | + n²::Int |
| 19 | + transpose_inds::Vector{Int} # maps the linear indices of n×n matrix *B* to the indices of matrix *B'* |
| 20 | + |
| 21 | + CommutationMatrix(n::Integer) = new(n, n^2, transpose_linear_indices(n)) |
| 22 | +end |
| 23 | + |
| 24 | +Base.size(A::CommutationMatrix) = (A.n², A.n²) |
| 25 | +Base.size(A::CommutationMatrix, dim::Integer) = |
| 26 | + 1 <= dim <= 2 ? A.n² : throw(ArgumentError("invalid matrix dimension $dim")) |
| 27 | +Base.length(A::CommutationMatrix) = A.n²^2 |
| 28 | +Base.getindex(A::CommutationMatrix, i::Int, j::Int) = j == A.transpose_inds[i] ? 1 : 0 |
| 29 | + |
| 30 | +function Base.:(*)(A::CommutationMatrix, B::AbstractMatrix) |
| 31 | + size(A, 2) == size(B, 1) || throw( |
| 32 | + DimensionMismatch("A has $(size(A, 2)) columns, but B has $(size(B, 1)) rows"), |
| 33 | + ) |
| 34 | + return B[A.transpose_inds, :] |
| 35 | +end |
| 36 | + |
| 37 | +function Base.:(*)(A::CommutationMatrix, B::SparseMatrixCSC) |
| 38 | + size(A, 2) == size(B, 1) || throw( |
| 39 | + DimensionMismatch("A has $(size(A, 2)) columns, but B has $(size(B, 1)) rows"), |
| 40 | + ) |
| 41 | + return SparseMatrixCSC( |
| 42 | + size(B, 1), |
| 43 | + size(B, 2), |
| 44 | + copy(B.colptr), |
| 45 | + A.transpose_inds[B.rowval], |
| 46 | + copy(B.nzval), |
| 47 | + ) |
| 48 | +end |
| 49 | + |
| 50 | +function LinearAlgebra.lmul!(A::CommutationMatrix, B::SparseMatrixCSC) |
| 51 | + size(A, 2) == size(B, 1) || throw( |
| 52 | + DimensionMismatch("A has $(size(A, 2)) columns, but B has $(size(B, 1)) rows"), |
| 53 | + ) |
| 54 | + |
| 55 | + @inbounds for (i, rowind) in enumerate(B.rowval) |
| 56 | + B.rowval[i] = A.transpose_inds[rowind] |
| 57 | + end |
| 58 | + return B |
| 59 | +end |
0 commit comments