# 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:** 3

<div class="post-metadata">

### Author: ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)
#### Post date: [August 26, 2020, 4:42pm UTC](https://discourse.julialang.org/t/computing-inverse-of-a-stack-of-matrices/45580/3 "2020-08-26T16:42:03Z")

</div>

> [@bhaveshshrimali](#):
>
> I was looking for an efficient way to invert a stack of 3x3 matrices.

Use an array of `SMatrix` (from StaticArrays.jl), which is about 25× faster (_update:_ 75× faster if I [fix my type declaration](https://discourse.julialang.org/t/computing-inverse-of-a-stack-of-matrices/45580/5)) than your `compute_inv` on my machine:

```julia
julia> using StaticArrays, BenchmarkTools

julia> A = rand(SMatrix{3,3,Float64}, 1000,4);

julia> @btime inv.($A);
  143.487 μs (4002 allocations: 593.83 KiB)

```

For such small matrices, generic routines that work for any size of matrix have a lot of overhead. The advantage of StaticArrays is huge here because it lets you invoke an unrolled, [optimized inversion routine specifically for 3×3 matrices](https://github.com/JuliaArrays/StaticArrays.jl/blob/ad583c99768f3a381ba20b1a0782c9ca50890b50/src/inv.jl#L16-L31).

~~(I’m still surprised that it is reporting 4002 allocations, however; not sure why it requires a heap allocation for each element.)~~ _Update_: I should have used `SMatrix{3,3,Float64,9}` as [explained below](https://discourse.julialang.org/t/computing-inverse-of-a-stack-of-matrices/45580/5).

(Note also that `randn(1000,4,3,3)` puts the dimensions in the wrong order for locality — you probably want the 3x3 matrices to be contiguous in memory. Storing things as an array of StaticArrays gets you contiguity automatically.)

---

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