# Efficiently Calculate Matrices Defined Recursively

**URL:** https://discourse.julialang.org/t/efficiently-calculate-matrices-defined-recursively/25006
**Category:** Performance
**Created:** [June 6, 2019, 12:39pm UTC](https://discourse.julialang.org/t/efficiently-calculate-matrices-defined-recursively/25006 "2019-06-06T12:39:23Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![Joseph\_Saia](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/joseph_saia/32/8769_2.png) [@Joseph\_Saia](https://discourse.julialang.org/u/Joseph_Saia)
#### Post date: [June 6, 2019, 12:39pm UTC](https://discourse.julialang.org/t/efficiently-calculate-matrices-defined-recursively/25006/1 "2019-06-06T12:39:23Z")

</div>

In my work I frequently have to calculate a long sequence (about N=10^6) of small matrices (about 3x3) that are defined recursively like `X_t = f(X_{t-1})`. The object of interest is the entire chain of matrices so I need to calculate and save each of them. I can usually write an efficient version of `f()` that can do all the calculations in place. A simplified version of this algorithm is below. My main question is what is the most efficient way to store the sequence of matrices `X` and to access each sub matrix `X` as I iterate through the chain. I’ve tried several different ways of laying out the `X` object but haven’t found a way that doesn’t lead to a bunch of allocations along in the for loop. Thanks.

```julia
using LinearAlgebra
function update!(X, A)
    for k in 2:100
        @views mul!(X[:,:,k], X[:,:,k - 1], A)
    end
end
function run()
    X = ones(2, 2, 100)
    A = [0.5 0.5; 0.25 0.75]
    @time update!(X, A)
end
run()

```

---

<div class="post-metadata">

### Author: ![ericphanson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ericphanson/32/215186_2.png) [@ericphanson](https://discourse.julialang.org/u/ericphanson)
#### Post date: [June 6, 2019, 12:48pm UTC](https://discourse.julialang.org/t/efficiently-calculate-matrices-defined-recursively/25006/2 "2019-06-06T12:48:11Z")

</div>

This sounds perfect for a vector of [StaticArrays](https://github.com/JuliaArrays/StaticArrays.jl)! If you need mutability you can use `MArray`‘s, but it will likely be faster by just doing out of place operations on `SArray`‘s.
