How to Shuffle the Rows of a 2D Matrix in MATLAB

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


Create a matrix using the following code:

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


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

  1. Get the number of rows of the matrix
  2. Generate random row indices
  3. Access the matrix using the indices obtained in Step 2
% Shuffle the rows of A
[r,~] = size(A); % Step 1
randomRowIdxs = randperm(r); % Step 2
resultExample1 = A(randomRowIdxs,:); % Step 3


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

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

Further reading

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

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    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.


Your friends may need this knowledge to complete a task. Share this tutorial.