JULIA : How to permute randomly a vector in julia?

好久不见. 提交于 2019-12-11 01:57:49

问题


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

the returned error is : ERROR: MethodError: no method matching randperm(::Array{Float64,1}) in eval(::Module, ::Any) at ./boot.jl:237

Thank you


回答1:


Based on the docs the 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 = collect(1:5)
5-element Array{Int64,1}:
 1
 2
 3
 4
 5

julia> Y = X[randperm(length(X))]
5-element Array{Int64,1}:
 3
 4
 1
 2
 5

You can always check the docs by typing ?function_name in the REPL.

If your only goal is to randomly permute the vector, you can also use shuffle():

julia> shuffle(X)
5-element Array{Int64,1}:
 5
 4
 1
 2
 3



回答2:


To piggyback on the second point in the answer by @niczky12, if you want to randomly permute the vector X directly then it is actually more efficient to call shuffle!(X) instead of shuffle(X):

# precompile @time
@time 1+1

# create random vector
p = 10_000
X = collect(1:p)

# reproducible shuffles
srand(2016)

shuffle(X)
@time shuffle(X)

shuffle!(X)
@time shuffle!(X)

Output on my machine:

  0.000004 seconds (148 allocations: 10.151 KB)
  0.000331 seconds (6 allocations: 78.344 KB)
  0.000309 seconds (4 allocations: 160 bytes)

The call to shuffle! allocates substantially less memory (160 bytes v. 78 Kb) and thus will scale better with p.



来源:https://stackoverflow.com/questions/38010052/julia-how-to-permute-randomly-a-vector-in-julia

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!