JULIA:如何在 Julia 中随机排列一个向量? [英] JULIA : How to permute randomly a vector in julia?

查看:17
本文介绍了JULIA:如何在 Julia 中随机排列一个向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个随机数向量,我想使用如下所示的 randperm() 函数随机排列,但它不起作用.

l have a vector of random numbers that l want to permute randomly using randperm() function as follows but it's not working.

X=rand(100000) # a vector of 100000 random elements
Y=randperm(X) # want to permute randomly the vector x

返回的错误是:错误:MethodError:没有方法匹配 randperm(::Array{Float64,1})在 eval(::Module, ::Any) 中 ./boot.jl:237

谢谢

推荐答案

使用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!():

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() 接受整数 n 并给出长度为 n 的排列.您可以使用此排序来重新排序原始向量:

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

奖励:无需替换即可采样

您也可以使用 StatsBase.sample() 从数组中采样相同的 length(X) 元素而不进行替换:

julia> import StatsBase;

julia> StatsBase.sample(X, length(X), replace=false)
5-element Vector{Int64}:
 5
 2
 4
 1
 3

这篇关于JULIA:如何在 Julia 中随机排列一个向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆