# Computing Inverse of a stack of matrices

**URL:** <https://discourse.julialang.org/t/computing-inverse-of-a-stack-of-matrices/45580>\
**Category:** General Usage\
**Tags:** performance, linearalgebra\
**Created:** [August 26, 2020, 4:23pm UTC](https://discourse.julialang.org/t/computing-inverse-of-a-stack-of-matrices/45580 "2020-08-26T16:23:17Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![mcabbott](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mcabbott/32/6603_2.png) [@mcabbott](https://discourse.julialang.org/u/mcabbott)\
**Post date:** [August 26, 2020, 4:38pm UTC](https://discourse.julialang.org/t/computing-inverse-of-a-stack-of-matrices/45580/2 "2020-08-26T16:38:34Z")

</div>

If you have lots of tiny matrices, then StaticArrays is usually a good idea:

```julia
@btime compute_inv(A) setup=(A = randn(1000,4,3,3)); # 1.928 ms

function slice_inv(A) # expects matrix indices first
    B = similar(A)
    @inbounds for j in axes(A,4)
        for i in axes(A,3)
            B[:,:,i,j] .= inv(@view A[:,:,i,j]);
        end
    end
    B
end

@btime slice_inv(A) setup=(A = randn(3,3,4,1000)); # 1.260 ms

using StaticArrays

function slice_inv2(A::Array{T,4}) where {T}
    B = reinterpret(SArray{Tuple{3,3},T,2,9}, vec(A))
    C = map(inv, B)
    reshape(reinterpret(T, B), size(A))
end

@btime slice_inv2(A) setup=(A = randn(3,3,4,1000)); # 43.037 μs

```

---

_[View the full topic](https://discourse.julialang.org/t/computing-inverse-of-a-stack-of-matrices/45580)._
