Tutorial

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

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

Preparation

Create a matrix using the following code:

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

Procedure

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

  1. Get the number of columns of the matrix
  2. Generate random column indices
  3. Access the matrix using the indices obtained in Step 2
% Shuffle the columns of A
c = size(A,2); % Step 1
randomColIdxs = randperm(c); % Step 2
resultExample1 = A(:,randomColIdxs); % 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 = shufflecols(A)
c = size(A,2);
randomColIdxs = randperm(c);
B = A(:,randomColIdxs);
end

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

The file ‘shufflecols.m’ must be in the current directory or in the MATLAB search path.
% Shuffle the columns of A again
resultExample2 = shufflecols(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 columns of a 2D 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.