Tutorial

How to Shuffle a Matrix in MATLAB

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

Preparation

Create two matrices using the following code:

A = [9, 4, 7; 1, 11, 3];
B = [4, 15, 6, 8, 10, 1, 2, 9, 5, 7, 14, 3];
B = reshape(B,2,3,2);

Procedure

Apply this procedure to randomize the order of the elements in a matrix:

  1. Get the linear indices of the matrix in random order
  2. Get the matrix as a vector using the indices obtained in Step 1
  3. Reshape the vector according to the size of the matrix
This procedure works for matrices of any size.
% Shuffle the matrix A
randomIdxsA = randperm(numel(A)); % Step 1
resultExample1 = reshape(A(randomIdxsA),size(A)); % Steps 2 and 3

Function

The following function encapsulates the procedure described above. It is properly documented and available for download here.

function B = shuffle(A)
randomIdxsA = randperm(numel(A));
B = reshape(A(randomIdxsA),size(A));
end

To use shuffle, pass a matrix of any size. The function will randomize the order of the elements in the matrix, and will store the result in the output argument.

The file ‘shuffle.m’ must be in the current directory or in the MATLAB search path.
% Shuffle the matrix B
resultExample2 = shuffle(B);
% Shuffle the matrix B again
resultExample3 = shuffle(B);

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 a matrix in MATLAB. The source code developed in this tutorial is available at this page.

Share

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