Julia multiply each matrix along dim

julia, matrix-multiplication

Solution

If you are working with matrices, it may be appropriate to consider `x` as a vector of matrices instead of a 3D array. Then you could do

x = [rand(6,6) for _ in 1:2^10]
y = [rand(6)]
z = x .* y

`z` is now a vector of vectors.

And if `z` is preallocated, that would be

z .= x .* y

And, if you want it really fast, use vectors of `StaticArrays`

using StaticArrays

x = [@SMatrix rand(6, 6) for _ in 1:2^10]
y = [@SVector rand(6)]
z = x .* y

That's showing a 10x speedup on my computer, running in 12us.

Problem

I have a 3 dimensional array ``` x = rand(6,6,2^10) ``` I want to multiply each matrix along the third dimension by a vector. Is there a more clean way to do this than: ``` y = rand(6,1) z = zeros(6,1,2^10) for i in 1:2^10 z[:,:,i] = x[:,:,i] * y end ```

Original source