A shuffle operation randomizes the order of the elements in a matrix.

Preparation

Create a matrix using the following code:

``A = reshape(1:6,3,2);``

Procedure

Apply this procedure to randomize the order of the rows of a 2D matrix:

``````% Shuffle the rows of A
[r,~] = size(A); % Step 1
randomRowIdxs = randperm(r); % Step 2
resultExample1 = A(randomRowIdxs,:); % Step 3``````

Function

The following function encapsulates the procedure described above, but omits some validations. A full and properly documented version is available for download here.

``````function B = shufflerows(A)
[r,~] = size(A);
randomRowIdxs = randperm(r);
B = A(randomRowIdxs,:);
end``````

To use `shufflerows`, pass a 2D matrix. The function will randomize the order of the rows of the matrix, and will store the result in the output argument.

The file ‘shufflerows.m’ must be in the current directory or in the MATLAB search path.
``````% Shuffle the rows of A again
resultExample2 = shufflerows(A);``````

I recommend the following books to learn more on random numbers and matrix shuffling in MATLAB.

1. This book was the winner of a Textbook Excellence Award. The first chapter covers random numbers, logical operators, and common elementary math functions, among other topics.

2. MATLAB for Engineers (5th Edition)

This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. The third chapter covers random numbers, matrix sorting, and several data analysis functions, among other topics.

I also recommend the other tutorials in this series.

Source code

I hope you have learned how to shuffle the rows of a 2D matrix in MATLAB. The source code developed in this tutorial is available at this page.