Use shuffle()
如果您的唯一目标是随机排列向量,您可以使用shuffle() https://docs.julialang.org/en/v1/stdlib/Random/#Random.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() https://docs.julialang.org/en/v1/stdlib/Random/#Random.randperm接受一个整数n
并给出长度为 n 的排列。您可以使用此排序来重新排序原始向量:
julia> X[randperm(length(X))]
5-element Array{Int64,1}:
3
4
1
2
5
奖励:样品无需更换
您还可以使用StatsBase.sample() https://juliastats.org/StatsBase.jl/stable/sampling/#StatsBase.sample采样相同的length(X)
数组中的元素无需替换:
julia> import StatsBase;
julia> StatsBase.sample(X, length(X), replace=false)
5-element Vector{Int64}:
5
2
4
1
3