edgarmtze
edgarmtze

Reputation: 25048

Random order of rows Matlab

Say we have a matrix of size 100x3

How would you shuffle the rows in MATLAB?

Upvotes: 45

Views: 51346

Answers (4)

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.

Upvotes: 3

Rahul
Rahul

Reputation: 11

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

Upvotes: 1

KnowledgeBone
KnowledgeBone

Reputation: 1663

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)),:);

Upvotes: 6

Jonas
Jonas

Reputation: 74940

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.

Upvotes: 73

Related Questions