Create a matrix using the following code:
A = reshape(1:6,3,2);
A = 1 4 2 5 3 6
Apply this procedure to randomize the order of the rows of a 2D matrix:
- Get the number of rows of the matrix
- Generate random row indices
- 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
resultExample1 = 1 4 3 6 2 5
function B = shufflerows(A) [r,~] = size(A); randomRowIdxs = randperm(r); B = A(randomRowIdxs,:); end
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.
% Shuffle the rows of A again resultExample2 = shufflerows(A);
resultExample2 = 2 5 3 6 1 4
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.
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.