# How to reduce a (reshaped) sparse matrix to a max or sum with acceptable speed?

**URL:** https://discourse.julialang.org/t/how-to-reduce-a-reshaped-sparse-matrix-to-a-max-or-sum-with-acceptable-speed/112888
**Category:** Performance
**Created:** [April 12, 2024, 6:47pm UTC](https://discourse.julialang.org/t/how-to-reduce-a-reshaped-sparse-matrix-to-a-max-or-sum-with-acceptable-speed/112888 "2024-04-12T18:47:55Z")
**Posts on this page:** 1
**Showing post:** 4

<div class="post-metadata">

### Author: ![mikmoore](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mikmoore/32/31109_2.png) [@mikmoore](https://discourse.julialang.org/u/mikmoore)
#### Post date: [April 12, 2024, 8:29pm UTC](https://discourse.julialang.org/t/how-to-reduce-a-reshaped-sparse-matrix-to-a-max-or-sum-with-acceptable-speed/112888/4 "2024-04-12T20:29:04Z")

</div>

Clearly `view` and `reshape` of `SparseMatrixCSC` are not performing well. It gets tedious to write, but sometimes you can decompose the reduction into two parts with the first operating on a raw sparse array. If you are always reducing over the 4th dimension, for example, consider reducing over it first and then handle the others after.

Like this

```julia
sz4 = (300, 300, 36, 2 * 60 * 12)
sz2 = (sz4[1] * sz4[2] * sz4[3] , sz4[4])
activitygrid = sprand(Float32, sz2..., 111f-6)

# reduce over 4th dim, then 3rd
max34 = dropdims(maximum(reshape(maximum(activitygrid; dims=2), sz4[1:3]); dims=3); dims=3)
# 1.2s on my machine

```

If you need fancier reductions, consider different storage options, like `(dim1, dim2*dim3*dim4)`, that might better reflect your uses. With some post-processing you can usually make these things work, although it sometimes reeks of MATLAB-style index gymnastics.

---

_[View the full topic](https://discourse.julialang.org/t/how-to-reduce-a-reshaped-sparse-matrix-to-a-max-or-sum-with-acceptable-speed/112888)._
