利用shuffle()
如果您的唯一目标是随机排列向量,则可以使用shuffle()
(Random
模块的一部分):
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
如果您不想分配新向量,但想就地洗牌,您可以使用shuffle!()
:
julia> shuffle!(X);
julia> X
5-element Vector{Int64}:
3
4
2
5
1
randperm()
randperm()
接受一个整数n
并给出长度为 n 的排列。您可以使用此排序来重新排序原始向量:
julia> X[randperm(length(X))]
5-element Array{Int64,1}:
3
4
1
2
5
奖励:无需更换即可采样
您还可以使用从数组StatsBase.sample()
中采样相同的元素而无需替换:length(X)
julia> import StatsBase;
julia> StatsBase.sample(X, length(X), replace=false)
5-element Vector{Int64}:
5
2
4
1
3