# How to make faster in a matrix multiplication inside a loop?

**URL:** https://discourse.julialang.org/t/how-to-make-faster-in-a-matrix-multiplication-inside-a-loop/43783
**Category:** Performance
**Created:** [July 27, 2020, 6:21pm UTC](https://discourse.julialang.org/t/how-to-make-faster-in-a-matrix-multiplication-inside-a-loop/43783 "2020-07-27T18:21:25Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![jmcastro2109](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jmcastro2109/32/38427_2.png) [@jmcastro2109](https://discourse.julialang.org/u/jmcastro2109)
#### Post date: [July 27, 2020, 6:21pm UTC](https://discourse.julialang.org/t/how-to-make-faster-in-a-matrix-multiplication-inside-a-loop/43783/1 "2020-07-27T18:21:25Z")

</div>

Hi!

Is there a way to implement the following function faster?

```julia
Seeds = rand(200,90,15000,10)
Mat = rand(200,200)

@views function testfunction(Seeds,Mat)
    
    (J,T,N,S) = size(Seeds)
    ν = zeros(Float32,J,T,N,S)
    W=0.75.*exp.((-0.003).*Mat)
    W[diagind(W)] .= 1
    C=cholesky(W)
    Ctemp = copy(C.L)
    @inbounds for n=1:N, s=1:S, t=1:T
        ν[:,t,n,s] = Ctemp*Seeds[:,t,n,s]
    end
    return ν
end

```

It usually takes around

92.284776 seconds (26.64 M allocations: 29.804 GiB, 3.92% gc time)

---

<div class="post-metadata">

### Author: ![Oscar\_Smith](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oscar_smith/32/25343_2.png) [@Oscar\_Smith](https://discourse.julialang.org/u/Oscar_Smith)
#### Post date: [July 27, 2020, 6:30pm UTC](https://discourse.julialang.org/t/how-to-make-faster-in-a-matrix-multiplication-inside-a-loop/43783/2 "2020-07-27T18:30:36Z")

</div>

This should be faster on Julia 1.5/master since there the views won’t allocate.Changing your structure so that `J` is you right-most index will also help, as it will make things go in memory order.

---

<div class="post-metadata">

### Author: ![antoine-levitt](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/antoine-levitt/32/4008_2.png) [@antoine-levitt](https://discourse.julialang.org/u/antoine-levitt)
#### Post date: [July 27, 2020, 6:48pm UTC](https://discourse.julialang.org/t/how-to-make-faster-in-a-matrix-multiplication-inside-a-loop/43783/3 "2020-07-27T18:48:19Z")

</div>

You’ll want to send that whole loop to BLAS. Reshape so that (t,n,s) is just one dimension, then just do `ν = C.L*Seeds` (without need for preallocating or copying). Also you’re doing mixed float32 and float64, which BLAS might not like, so I’d advise you to choose one precision for the computational bottleneck and stick with it. Also profile to make sure that the bottleneck is indeed where you think it is.
