How to broadcast rand(lb:ub)?

As from the title, how do I broadcast rand(lowerbound:upperbound) ?

e.g.

x = [1,2,3]
a = 2 .* x .+ rand.()   # ok
a = @. 2x + rand()      # ok
a = @. 2x + rand(1:2)   # DimensionMismatch error

BDW, I am aware of a = 2 .* x .+ rand(1:2,length(x)), but is there a more elegant solution (I would like to keep the @. macro) ?

Put it in a container, like a 1-element tuple, to treat 1:2 as a “scalar” for broadcasting:

julia> @. 2x + rand((1:2,))
3-element Vector{Int64}:
 3
 6
 7

(This is not only less “elegant” but it also allocates an additional temporary array.)

That’s a bit odd: why here the Ref() trick doesn’t work ?

e.g.:

a = @. 2x + rand(Ref(1:2))    # error
foo(x,y) = y[1] + x * y[2]
foo.([0,10,100],Ref([100,1])) # fine here

Because Ref is also broadcast ed in a macro. Try one of

a = 2x .+ rand.(Ref(1:2))
a = @. 2x + rand($(1:2))

@. Ref(x) is also broadcasting Ref, defeating the whole point of it.

This works:

julia> @. 2x + rand($Ref(1:2))
3-element Vector{Int64}:
 3
 6
 8

(Splicing a function call with $ prevents it from being broadcasted by @..)

This allocates a temporary array for 2x.

This doesn’t work: $(1:2) is equivalent to 1:2 in the @..