# Broadcasting sampling of the variable size

**URL:** https://discourse.julialang.org/t/broadcasting-sampling-of-the-variable-size/71632
**Category:** General Usage
**Tags:** broadcast
**Created:** [November 17, 2021, 4:27am UTC](https://discourse.julialang.org/t/broadcasting-sampling-of-the-variable-size/71632 "2021-11-17T04:27:11Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![Oko](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oko/32/22734_2.png) [@Oko](https://discourse.julialang.org/u/Oko)
#### Post date: [November 17, 2021, 4:27am UTC](https://discourse.julialang.org/t/broadcasting-sampling-of-the-variable-size/71632/1 "2021-11-17T04:27:12Z")

</div>

I would like to use `broadcast` to do repetitive sampling from an array with the added twist that samples are of variable sizes. In plain English I would like to replace the following `for` loop with a fancy code

```julia
using StatsBase
myspace = 1:10
for j = 3:1:5
      println(sample(myspace,j; replace=false, ordered=true))
end

```

Any hints? This seems trivial but I can wrap my mind around it.

---

<div class="post-metadata">

### Author: ![sijo](https://avatars.discourse-cdn.com/v4/letter/s/da6949/32.png) [@sijo](https://discourse.julialang.org/u/sijo)
#### Post date: [November 17, 2021, 8:02am UTC](https://discourse.julialang.org/t/broadcasting-sampling-of-the-variable-size/71632/2 "2021-11-17T08:02:13Z")

</div>

Maybe you’re looking for this:

```julia
julia> sample.(Ref(myspace), 3:5; replace=false, ordered=true)
3-element Vector{Vector{Int64}}:
 [4, 5, 7]
 [3, 4, 6, 10]
 [2, 3, 6, 9, 10]

```

Here I use `Ref` to “escape” `myspace` from broadcasting. If I write `sample(myspace, 3:5)` it will broadcast on both `myspace` and `3:5`. Wrapping with `Ref` is like creating a container with one element, so it broadcasts on `Ref(myspace)` which has just a single value `myspace` in it.

Equivalently you could do

```julia
sample.((myspace,), 3:5; replace=false, ordered=true)

```

or

```julia
sample.([myspace], 3:5; replace=false, ordered=true)

```
