3
votes

How can I pass an array containing the dimensions I desire to a function like ones or rand in Julia?

For example, I'd like to execute

dims = [3 4]
rand(dims)

and then receive something like

3×4 Array{Float64,2}:
 0.300811  0.140124  0.756915   0.268328 
 0.732461  0.900773  0.251334   0.0338452
 0.54227   0.439385  0.0812104  0.612996 

as the output.

Executing the first code block returns a single number selected at random from the array dimen = [3 4], however, and rand(dims = dimen) returns a ERROR: function rand does not accept keyword arguments error.

Is there a way to do what I'm hoping to?

2

2 Answers

4
votes

What you are looking for is the "splat" operator ..., as described in the documentation:

On the flip side, it is often handy to "splat" the values contained in an iterable collection into a function call as individual arguments. To do this, one also uses ... but in the function call instead

In your case:

julia> dims = [3 4];
julia> rand(dims...)

3×4 Array{Float64,2}:
 0.664496  0.190208  0.167208  0.172296
 0.632465  0.374373  0.417636  0.354948
 0.743741  0.740435  0.602339  0.401814
3
votes

Use the splat operator:

julia> xs = [3 4]
1×2 Array{Int64,2}:
 3  4

julia> rand(xs...)
3×4 Array{Float64,2}:
 0.569082   0.953     0.44541   0.12763 
 0.0529293  0.470243  0.770411  0.992597
 0.15326    0.248442  0.805518  0.246996

The splat operator will interpolate the array into the function call's argument list.