rand!

rand!([rng], A, [coll])

Populate the array A with random values. If the indexable collection coll is specified, the values are picked randomly from coll. This is equivalent to copy!(A, rand(rng, coll, size(A))) or copy!(A, rand(rng, eltype(A), size(A))) but without allocating a new array.

Examples

  1. Generate an array of random numbers:

    julia> arr = zeros(5);
    julia> rand!(arr)
    5-element Array{Float64,1}:
    0.543383
    0.829725
    0.987295
    0.236186
    0.981393

    This example populates the array arr with random floating-point numbers between 0 and 1.

  2. Generate an array of random integers:

    julia> arr = zeros(Int, 4);
    julia> rand!(arr)
    4-element Array{Int64,1}:
    2
    1
    3
    2

    It populates the array arr with random integers.

  3. Generate an array of random values from a given collection:
    julia> coll = [10, 20, 30, 40, 50];
    julia> arr = zeros(Int, 3);
    julia> rand!(arr, coll)
    3-element Array{Int64,1}:
    40
    20
    30

    This example populates the array arr with random values picked randomly from the collection coll.

Common mistake example:

julia> arr = [1, 2, 3];
julia> rand!(arr, [10, 20])
ERROR: DimensionMismatch("array size 3 does not match number of sampled elements 2")

In this example, the size of the array arr does not match the number of elements to be sampled from the collection. Ensure that the size of the array matches the number of elements you want to sample.

See Also

Array, broadcast, cat, combinations, conj!, digits!, fieldnames, fill, fill!, last, length, maximum, minimum, ones, parent, parentindexes, partitions, permutations, pointer, pointer_to_array, promote_shape, rand!, reshape, scale, similar, sum, sum_kbn, takebuf_array, transpose!, vec, zeros,

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: