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

**URL:** <https://discourse.julialang.org/t/storing-a-batch-of-sparse-matrices-and-multiplying-them-to-a-vector/106646>\
**Category:** General Usage\
**Tags:** sparse\
**Created:** [November 23, 2023, 7:58pm UTC](https://discourse.julialang.org/t/storing-a-batch-of-sparse-matrices-and-multiplying-them-to-a-vector/106646 "2023-11-23T19:58:48Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![eveningsilverfox](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/eveningsilverfox/32/51932_2.png) [@eveningsilverfox](https://discourse.julialang.org/u/eveningsilverfox)\
**Post date:** [November 23, 2023, 7:58pm UTC](https://discourse.julialang.org/t/storing-a-batch-of-sparse-matrices-and-multiplying-them-to-a-vector/106646/1 "2023-11-23T19:58:48Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![SteffenPL](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/steffenpl/32/206270_2.png) [@SteffenPL](https://discourse.julialang.org/u/SteffenPL)\
**Post date:** [November 24, 2023, 1:07am UTC](https://discourse.julialang.org/t/storing-a-batch-of-sparse-matrices-and-multiplying-them-to-a-vector/106646/2 "2023-11-24T01:07:07Z")

</div>

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

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

```

for the batch computation you can do

```julia
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.
