JULIA : How to permute randomly a vector in julia?

vincet picture vincet · Jun 24, 2016 · Viewed 9.4k times · Source

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

Answer

niczky12 picture niczky12 · Jun 24, 2016

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