Yuseferi
Yuseferi

Reputation: 8670

shuffle matrix element in matlab

I have a martix and want to shuffle element of it .

x=[1 2 5 4 6 ]

after shuffle(something like this)

x=[2 4 6 5 1]    

is matlab has function for it ? in php array_shuffle do this.

Upvotes: 13

Views: 16521

Answers (2)

abcd
abcd

Reputation: 42225

As an alternate to randperm, you can also use randsample from the statistics toolbox.

y = randsample(n,k) returns a k-by-1 vector y of values sampled uniformly at random, without replacement, from the integers 1 to n.

Note that it is "without replacement" (by default). So if you set k as length(x), it is equivalent to doing a random shuffle of the vector. For example:

x = 1:5;
randsample(x,length(x))
%ans = 
%       4     5     3     1     2

I like this more than randperm, because it is easily extensible to different uses. For example, to draw 3 elements from x at random (like drawing from a bucket with finite items), you do randsample(x,3). Likewise, if you wish to draw 3 numbers, where the alphabet is made up of the elements of x, but allow for repetitions, you do randsample(x,3,true).

Upvotes: 7

Acorbe
Acorbe

Reputation: 8391

  1. obtain shuffled indices using randperm

    idx = randperm(length(x));
    
  2. use indices to obtain shuffled vector

    xperm = x(idx);

Upvotes: 25

Related Questions