Create a matrix using the following code:
A = reshape(1:6,2,3);
A = 1 3 5 2 4 6
Apply this procedure to randomize the order of the columns of a 2D matrix:
- Get the number of columns of the matrix
- Generate random column indices
- 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
resultExample1 = 3 5 1 4 6 2
function B = shufflecols(A) c = size(A,2); randomColIdxs = randperm(c); B = A(:,randomColIdxs); end
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.
% Shuffle the columns of A again resultExample2 = shufflecols(A);
resultExample2 = 5 3 1 6 4 2
I recommend the following books to learn more on random numbers and matrix shuffling in MATLAB.
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.
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.
- How to Shuffle a Matrix in MATLAB
- How to Shuffle the Rows of a 2D Matrix in MATLAB
- How to Shuffle the Columns of a 2D Matrix in MATLAB
- How to Shuffle the Elements Within the Rows of a 2D Matrix in MATLAB
- How to Shuffle the Elements Within the Columns of a 2D Matrix in MATLAB
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.