Best way to multiply each row of a matrix by a random number
I would like to multiply each row of a matrix by a random number, for example.
Y = R*X
diagonal matrix with R
a size TxN
containing entries from rand()
and matrix X
size NxM
with a very large T
and N
. I am currently using
r = rand(T)
Y = scale(r, X)
but I'm wondering if it will be done faster or better. For example, I think there is no need to create a vector R
, but I don't know how I can efficiently call y[i] = rand()*X[i,:]
/ parallel.
source to share
You can use scale!
to change X
in place:
julia> X = [ 1/(i + j - 1) for i=1:5, j=1:5 ]
5x5 Array{Float64,2}:
1.0 0.5 0.333333 0.25 0.2
0.5 0.333333 0.25 0.2 0.166667
0.333333 0.25 0.2 0.166667 0.142857
0.25 0.2 0.166667 0.142857 0.125
0.2 0.166667 0.142857 0.125 0.111111
julia> r = rand(5)
5-element Array{Float64,1}:
0.98996
0.88145
0.808518
0.632665
0.00807468
julia> scale!(r,X);
julia> X
5x5 Array{Float64,2}:
0.98996 0.49498 0.329987 0.24749 0.197992
0.440725 0.293817 0.220363 0.17629 0.146908
0.269506 0.20213 0.161704 0.134753 0.115503
0.158166 0.126533 0.105444 0.0903807 0.0790832
0.00161494 0.00134578 0.00115353 0.00100933 0.000897187
This avoids allocating a new matrix, which is a significant saving in both memory and time.
source to share