Fast sum of two sparse matrices and the Hadamard product of sparse and dense matrices

Hello all,

I would like to obtain the sum of two sparse matrices (see question 1) and the Hadamard product of a sparse matrix and a dense matrix (see question 2). Below is my current implementation. However, it is quite slow and has memory allocations. Is there a simple way to do both problems fast and without memory allocation? Thank you very much in advance!


v = 580
b = 18
q = 43416
# question 1:
Nr = sprandn(v, b, 0.20)
aIdx = rand(1:b,q)
bIdx = rand(1:b,q)
Y = similar(Nr[:,aIdx]);
f!(Y, Nr, aIdx, bIdx) = Y .= Nr[:,aIdx] .- Nr[:,bIdx]
@btime f!($Y, $Nr, $aIdx, $bIdx);

# question 2:
P = sprandn(v, q, 0.20);
K = rand(v,q);
Y = similar(P);

g1(Y, P, K) = Y .= P.*K
function g2(Y, P, K)
    v = size(Y,1)
    I,J,V = findnz(P)        
    idx = I .+ v.*(J.-1)
    Y[idx] = V.*view(K,idx)
end
@btime g1($Y, $P, $K);
@btime g2($Y, $P, $K);