SparseMatrixCSC in Julia?

Hi, I’m curious about this SparseMatrixCSC object in Julia. The following is the constructor. I was wondering, how to understand that “The row indices in every column need to be sorted. If your SparseMatrixCSC object contains unsorted row indices, one quick way to sort them is by doing a double transpose.” ?

struct SparseMatrixCSC{Tv,Ti<:Integer} <: AbstractSparseMatrix{Tv,Ti}
    m::Int                  # Number of rows
    n::Int                  # Number of columns
    colptr::Vector{Ti}      # Column i is in colptr[i]:(colptr[i+1]-1)
    rowval::Vector{Ti}      # Row indices of stored values
    nzval::Vector{Tv}       # Stored values, typically nonzeros

Thank you a lot for your time and attention !

When trying to access A[j,i], then colptr[i]:(colptr[i+1]-1) is the range of indices where the values (nzval) and row indices (rowval) are stored. Next, we need to find j in rowval[lo:hi].

rowval[lo:hi] is kept sorted, in order to permit binary search (log time). If you somehow end up with a SparseMatrixCSC that violates this invariant, then A[j,i] can give wrong answers (return zero, even if a nonzero entry exists). The comment about double transpose gives a quick-and-dirty trick to recover from such an invalid situation.

1 Like