Creating an array/matrix with a specified range of randomly generated numbers

Hello,

How would someone create a 5x5 array (matrix?) with randomly generated values of 0 or 1 (in Julia 1.0)?

And, if someone could clarify the difference between an array and matrix:

Array: numbers that can be grouped horizontally, vertically, or both ?
Matrix: numbers grouped both horizontally and vertically ?

Thank you!

EDIT ON: I’ll edit my answer for future reference as it is the most visible. As others have suggested below, the easiest way to do this is to just write

julia> rand([0, 1], 5, 5)
5×5 Array{Int64,2}:
 0  1  0  0  0
 0  1  0  0  1
 0  1  0  0  0
 0  0  0  0  0
 1  1  1  1  0

or, alternatively, rand(0:1, 5, 5).
EDIT OFF: I’ll leave the rest of the post as it is. It might be still instructive about the use of dots and conversions.

You can create a 5x5 array of randomly generated values between 0 and 1 with:

julia> rand(5,5)
5×5 Array{Float64,2}:
 0.974959  0.898156  0.639462   0.599058   0.360013
 0.368191  0.322947  0.156321   0.762705   0.16691 
 0.977952  0.578899  0.0581204  0.470908   0.81315 
 0.505665  0.858624  0.39044    0.0380672  0.640897
 0.36901   0.508695  0.737936   0.0884765  0.311747

Now you can round() them and, to make sure the rounding is done “element-wise”, use the dot notation:

julia> round.(rand(5,5))
5×5 Array{Float64,2}:
 0.0  1.0  1.0  0.0  1.0
 1.0  1.0  0.0  0.0  0.0
 1.0  0.0  0.0  0.0  0.0
 0.0  1.0  1.0  1.0  0.0
 1.0  1.0  0.0  1.0  0.0

Notice that, if you need the 0 and 1 to be integers instead of floats you can either do Int.(round.(rand(5,5))) or Int.(rand(Bool,5,5)) (the latter will generate a 5x5 matrix of trues and falsess which can then be converted into zeros and ones.

There is no deep difference between an array and a matrix. A matrix is just a name for two-dimensional array (in the same way a vector is just a name for a one-dimensional array). In fact:

julia> typeof(Matrix(undef,5,5))
Array{Any,2}

Here is a link to the docs for the dotted syntax https://docs.julialang.org/en/stable/manual/mathematical-operations/#man-dot-operators-1
and also a blog post (if you want to know more): https://julialang.org/blog/2017/01/moredots
For more on arrays you can check the documentation: https://docs.julialang.org/en/stable/manual/arrays/

1 Like

You can also tell round what type you want it to return as the first argument, so this also works:

julia> round.(Int, rand(5,5))
5×5 Array{Int64,2}:
 1  0  1  0  1
 0  0  0  0  1
 1  0  1  1  1
 0  1  1  1  1
 0  0  1  0  0
1 Like

Maybe is misunderstood something but why not use rand([0, 1], 5,5)?

5 Likes

I kinda like

rand(0:1, 5, 5)
7 Likes

Yeah, that’s easier. I had forgotten you can also specify a range within rand.