Julia multiplies each matrix along dim

I have a three dimensional array

x = rand(6,6,2^10)

I want to multiply each matrix along the third dimension by a vector. Is there a cleaner 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
+6
source share
3 answers

If you are working with matrices, it may be appropriate to consider xas 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 zpre-allocated, it will be

z .= x .* y

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

using StaticArrays

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

This shows a 10x speedup on my computer, running at 12us.

+6
source

mapslices(i->i*y, x, (1,2)) may be cleaner, but it will be slower.

: "times by y" .

function tst(x,y)
   z = zeros(6,1,2^10)
   for i in 1:2^10
       z[:,:,i] = x[:,:,i] * y
   end
   return z
end

tst2(x,y) = mapslices(i->i*y, x, (1,2))

time tst(x,y);0.002152 (4.10 k : 624.266 KB)

@time tst2(x,y);0,005720 (13,36 k : 466,969 KB)

+7

sum(x.*y',2) - .

. , , . x [:,:, i] y [i] x [:, i,:]. :

const x = rand(6,6,2^10);
const y = rand(6,1);
function tst(x,y)
    z = zeros(6,1,2^10)
    for i in 1:2^10
        z[:,:,i] = x[:,:,i]*y
    end
    return z
end
tst2(x,y) = mapslices(i->i*y,x,(1,2))
tst3(x,y) = sum(x.*y',2)

:

julia> using BenchmarkTools
julia> z = tst(x,y); z2 = tst2(x,y); z3 = tst3(x,y);
julia> @benchmark tst(x,y)
  BenchmarkTools.Trial: 
    memory estimate:  688.11 KiB
    allocs estimate:  8196
    --------------
    median time:      759.545 μs (0.00% GC)
    samples:          6068
julia> @benchmark tst2(x,y)
  BenchmarkTools.Trial: 
    memory estimate:  426.81 KiB
    allocs estimate:  10798
    --------------
    median time:      1.634 ms (0.00% GC)
    samples:          2869
julia> @benchmark tst3(x,y)
  BenchmarkTools.Trial: 
    memory estimate:  336.41 KiB
    allocs estimate:  12
    --------------
    median time:      114.060 μs (0.00% GC)
    samples:          10000

, tst3 sum (~ 7x tst ~ 15x tst2).

StaticArrays, @DNF, , .

+3

Source: https://habr.com/ru/post/1017015/


All Articles