# Why \`sprand\` does not accept a Distribution arg?

**URL:** https://discourse.julialang.org/t/why-sprand-does-not-accept-a-distribution-arg/127255
**Category:** General Usage
**Tags:** distributions, sparsearrays
**Created:** [March 22, 2025, 7:38am UTC](https://discourse.julialang.org/t/why-sprand-does-not-accept-a-distribution-arg/127255 "2025-03-22T07:38:30Z")
**Posts on this page:** 1
**Showing post:** 4

<div class="post-metadata">

### Author: ![gdalle](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gdalle/32/27854_2.png) [@gdalle](https://discourse.julialang.org/u/gdalle)
#### Post date: [March 22, 2025, 8:52am UTC](https://discourse.julialang.org/t/why-sprand-does-not-accept-a-distribution-arg/127255/4 "2025-03-22T08:52:28Z")

</div>

> [@WalterMadelim](#):
>
> Your code is a bit advanced for me,

Here it is with some comments:

```julia
# 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!

```

> [@WalterMadelim](#):
>
> maybe I will go with this

You can but it will be much less efficient in high dimension since you generate dense matrices before converting them to sparse format.

> [@WalterMadelim](#):
>
> If this is the case, I’ll suggest them to add this method. Since this is common in research work 🙂

If you want the devs to be aware of that, the best way is to open an issue on the Distributions.jl repo.

---

_[View the full topic](https://discourse.julialang.org/t/why-sprand-does-not-accept-a-distribution-arg/127255)._
