45

Say we have a matrix of size 100x3

How would you shuffle the rows in MATLAB?

edgarmtze
  • 24,683
  • 80
  • 235
  • 386
  • possible duplicate of [How do I randomly select k points from N points in MATLAB?](http://stackoverflow.com/questions/1856141/how-do-i-randomly-select-k-points-from-n-points-in-matlab) – Jonas Mar 26 '11 at 18:15
  • 2
    It is not about selecting, it is about "desorder" or shuffle the rows of a matrix – edgarmtze Mar 26 '11 at 18:16
  • 1
    Actually, you're right. It's not quite the same question. See my answer below. – Jonas Mar 26 '11 at 18:20

4 Answers4

73

To shuffle the rows of a matrix, you can use RANDPERM

shuffledArray = orderedArray(randperm(size(orderedArray,1)),:);

randperm will generate a list of N random values and sort them, returning the second output of sort as result.

Jonas
  • 74,690
  • 10
  • 137
  • 177
  • 3
    Your solution runs about 2.5x faster than mine does, at least on my computer. – KnowledgeBone Mar 26 '11 at 18:44
  • Thanks Jonas. Works like a charm. If you instead want to shuffle the columns of a matrix the solution is: shuffledArray = orderedArray(:,randperm(size(orderedArray,2))) – Rainymood Sep 07 '18 at 14:02
6

This can be done by creating a new random index for the matrix rows via Matlab's randsample function.

matrix=matrix(randsample(1:length(matrix),length(matrix)),:);
KnowledgeBone
  • 1,613
  • 2
  • 11
  • 13
  • 1
    I think you meant to use `'false'` - if sampling with replacement, the resulting matrix will contain duplicate rows, while others will have disappeared. In the case sampling without replacement, `randsample` calls `randperm`, which should thus only be marginally slower than calling `randperm` directly. – Jonas Mar 26 '11 at 19:19
3

While reading the answer of Jonas I found it little bit tough to read, tough to understand. In Mathworks I found a similar question where the answer is more readable, easier to understand. Taking idea from Mathworks I have written a function:

function ret = shuffleRow(mat)

[r c] = size(mat);
shuffledRow = randperm(r);
ret = mat(shuffledRow, :);

Actually it does the same thing as Jonas' answer. But I think it is little bit more readable, easier to understand.

1

For large datasets, you can use the custom Shuffle function

It uses D.E. Knuth's shuffle algorithm (also called Fisher-Yates) and the cute KISS random number generator (G. Marsaglia).

Bernhard
  • 3,619
  • 1
  • 25
  • 50
Rahul
  • 11
  • 1