Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In-place elementwise matrix multiplication aka Schur Product aka Hadamard Product?

I'm looking for an in-place implementation of elementwise matrix multiplication in Julia, aka the Schur Product aka the Hadamard product.

It can be performed with allocations by A .* B, but I cannot allocate additional memory every time I perform this operation.

Of course I could implement it myself, but I'd prefer the standard implementation if it exists.

Thanks

like image 999
Kyle Pena Avatar asked Mar 18 '23 06:03

Kyle Pena


1 Answers

I'm not aware on an in-place elementwise matrix multiplication, and I've had a good look in the julia/base/*.jl but can't find one. We have in-place matrix multiplication (e.g. A_mul_B!), but thats more important because we can use BLAS for that. Element-wise matrix multiplication doesn't use BLAS, AFAIK, so might as well use your own:

function had!{T<:Number}(A::Matrix{T},B::Matrix{T})
    m,n = size(A)
    @assert (m,n) == size(B)
    for j in 1:n
       for i in 1:m
         @inbounds A[i,j] *= B[i,j]
       end
    end
    return A
end

e.g.

julia> A = rand(2,2)
2x2 Array{Float64,2}:
 0.881304  0.916678
 0.590368  0.630032

julia> B = [2.0 3.0; 4.0 5.0]
2x2 Array{Float64,2}:
 2.0  3.0
 4.0  5.0

julia> had!(A,B);

julia> A
2x2 Array{Float64,2}:
 1.76261  2.75003
 2.36147  3.15016
like image 116
IainDunning Avatar answered Mar 19 '23 20:03

IainDunning