Use shuffle()
If your only goal is to randomly permute the vector, you can use shuffle()
(part of the Random
module):
julia> using Random;
julia> X = collect(1:5)
5-element Array{Int64,1}:
1
2
3
4
5
julia> shuffle(X)
5-element Array{Int64,1}:
5
4
1
2
3
If you don't want to allocate a new vector, but want to shuffle in place, you can use shuffle!()
:
julia> shuffle!(X);
julia> X
5-element Vector{Int64}:
3
4
2
5
1
randperm()
randperm()
accepts an integer n
and gives a permutation of length n. You can use this ordering to then reorder your original vector:
julia> X[randperm(length(X))]
5-element Array{Int64,1}:
3
4
1
2
5
Bonus: Sampling without replacement
You can also use StatsBase.sample()
to sample the same length(X)
elements from your array without replacement:
julia> import StatsBase;
julia> StatsBase.sample(X, length(X), replace=false)
5-element Vector{Int64}:
5
2
4
1
3