Storing a batch of sparse matrices and multiplying them to a vector

I store N matrices, each of size(n,n), in the array Batchm = zeros(ComplexF64, N,n,n ). Later, I retrieve the individual matrices and multiply to a vector, Batchm(index, :,:)*v.
The matrices are sparse and banded. What’s the best way to store them in a structure (like Batchm), for subsequent retrieval and multiplication?

If N is small in comparison to n, then using a vector of matrices might be the most convenient option, e.g.

batchm = [sprand(n,n,10) for i in 1:N]  
# type: Vector{SparseMatrixCSC{Float64,Int64}}

for the batch computation you can do

res = zeros(n)
for i in eachindex(batchm)
    res += batchm[i] * v
end

For banded matrices, there is also BandedMatrices.jl with a more specialized type which you could use instead of SparseMatixCSC.

Either way, it is probably much easier to use Vector{MatrixType} instead of increasing the dimension. Because if you add an extra dimension it is afterwards slower to get back a slice due to the way how sparse arrays work.

2 Likes