Because Distributions.jl didn’t implement it I guess. And in general you may need two sets of parameters, one for deciding which coefficients are nonzero and one for the distribution of these nonzero coefficients.
I guess you need to initialize a matrix first and then transform only its nonzeros:
Thank you very much.
Your code is a bit advanced for me, maybe I will go with this
import SparseArrays
import Distributions.Uniform as UDistri
import Distributions.Bernoulli as BDistri
function sp_rand(D, I, J, p)
Bmat, Mmat = rand(BDistri(p), I, J), rand(D, I, J)
return SparseArrays.sparse(Mmat .* Bmat)
end
If this is the case, I’ll suggest them to add this method. Since this is common in research work
# import necessary packages
using SparseArrays, Distributions, Random
# initialize a random number generator with a seed so that
# results are reproducible (not mandatory but good practice)
rng = Xoshiro(1)
# generate a Boolean "'mask" matrix to decide where the nonzeros are
M = sprand(rng, Bool, 10, 10, 0.5)
# allocate a matrix of the same size and nonzero structure
# but with a floating-point element type
N = similar(M, Float64)
# modify the non-zero coefficients of N in-place
# with the distribution of your choice
UD = Uniform(2, 3)
rand!(rng, UD, nonzeros(N));
# voila!
You can but it will be much less efficient in high dimension since you generate dense matrices before converting them to sparse format.
If you want the devs to be aware of that, the best way is to open an issue on the Distributions.jl repo.
I’m clearer now. But this is my first time learning about rand!, I’m still a bit confused.
If I want to in-place substitute the second row of a matrix, what should I do?
For the first time I know the usage of view (LOL).
The functionalities in Julia is something like:
if you don’t have an opportunity to use it, you’ll never have interests to learn it.
Yeah they might be superfluous indeed, I just wanted to show the conceptual difference between deciding the sparsity pattern (which can be done with Bool values) and drawing the actual coefficients.
I also didn’t know about rfn, which sounds like the right solution.