Preparation
Create a matrix using the following code:
A = reshape(25:39,3,5);
Procedure
Apply this procedure to randomize the order of the elements within the rows of a 2D matrix:
 Get the size of the matrix
 Get the row index of each element in the matrix
 Generate a random column index for each element in the matrix
 Get the linear indices equivalent to the subscripts obtained in Steps 2–3
 Access the matrix using the linear indices obtained in Step 4
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);
Example
Suppose that you need to shuffle the elements within the rows of A
.
% 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);
Function
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)
end
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.
% 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.

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.

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.