How to Shuffle the Elements Within 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(25:39,3,5);


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

  1. Get the size of the matrix
  2. Get the row index of each element in the matrix
  3. Generate a random column index for each element in the matrix
  4. Get the linear indices equivalent to the subscripts obtained in Steps 2–3
  5. Access the matrix using the linear indices obtained in Step 4
Steps 2–3 must produce a matrix of the same size as the original matrix.

The third step is the most important. To accomplish this step, create a matrix of random numbers of the same size as the original matrix, and sort it along the second dimension using the following code, where R is the random matrix:

[~,randomColIdxs] = sort(R,2);


Suppose that you need to shuffle the elements within the rows of A.

The third step involves random numbers, so your result in steps 3–5 may be different.
% Step 1
[height,width] = size(A);
% Step 2
rowIdxs = repmat((1:height)',1,width);
% Step 3
R = rand(height,width);
[~,randomColIdxs] = sort(R,2);
% Step 4
linearIdxs = sub2ind(size(A),rowIdxs,randomColIdxs);
% Step 5
resultExample1 = A(linearIdxs);


The function shufflewithinrows encapsulates the procedure described above. It is properly documented and available for download here. The signature of the function is as follows:

function B = shufflewithinrows(A)

To use shufflewithinrows, pass a 2D matrix. The function will randomize the order of the elements within each row, and will store the result in the output argument.

The file ‘shufflewithinrows.m’ must be in the current directory or in the MATLAB search path.
% Shuffle the elements within the rows of A
resultExample2 = shufflewithinrows(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 2017 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 elements within 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.