I have a function that spends most of its time in setindex! for sparse array. Part of the profiling results is
5339 ...rse/sparsematrix.jl:2316; setindex!(::SparseMatrixCSC{C...
5338 ./array.jl:852; insert!
10201 ...rse/sparsematrix.jl:2317; setindex!(::SparseMatrixCSC{C...
10200 ./array.jl:852; insert!(::Array{Complex{Float...
Any idea how to optimize this function? Is there anything like pre-allocation?
Use sparse(I, J, V,[ m, n, combine])
if you’re going to be building up a sparse array. Building them up by using setindex!
is just a bad idea given how they are stored, while building up the pairings (i,j,value)
is quick. Note that sparse matrices are not stored as (i,j,value)
since they are “compressed” (that’s what CSC means), and after they are compressed it’s not as easy to change the sparsity pattern. This storage is optimized for column slicing and matrix multiplication, but not for changing values (or slicing rows).
4 Likes