shuffle matrix element in matlab

后端 未结 2 1494
夕颜
夕颜 2020-12-03 17:32

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]    
         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 18:26

    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).

提交回复
热议问题