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