Convenience type for assembling sparse matrices

I find the IJV-approach to assembling sparse matrices quite cumbersome as it forces me to write three lines to set a single entry A[i,j] = v:

push!(I,i)
push!(J,j)
push!(V,v)

The situation becomes even worse if instead of a single entry I want to add a whole block of entries A[i1:i2, j1:j2] = v since then the entries of i1:i2 and j1:j2 have to be repeated.

I think it would be nice to have a convenience SparseMatrixAssembler type which wraps the IJV vectors and allows to use setindex! to achieve the above. Once you are done assembling, you simply call SparseMatrixCSC(assembler[,m,n]) to convert to a proper sparse matrix. For example:

julia> A = SparseMatrixAssembler();

julia> A[2,2] = π;

julia> SparseMatrixCSC(A,3,3)
3×3 SparseMatrixCSC{Float64,Int64} with 1 stored entry:
  [2, 2]  =  3.14159

A rough prototype implementation can be found at GitHub - ettersi/SparseMatrixAssemblers.jl: Assemble sparse matrices using block assignment. Any chance a more carefully designed version of this could make it into the standard SparseArrays package?

2 Likes