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

## Preparation

Create a matrix using the following code:

``A = reshape(25:39,5,3);``

## Procedure

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

1. Get the size of the matrix
2. Get the column index of each element in the matrix
3. Generate a random row index for each element in the matrix
4. Get the linear indices equivalent to the subscripts obtained in Steps 2–3
5. Access the matrix using the linear indices obtained in Step 4
Steps 2–3 must produce a matrix of the same size as the original matrix.

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 first dimension using the following code, where `R` is the random matrix:

``[~,randomRowIdxs] = sort(R,1);``

## Example

Suppose that you need to shuffle the elements within the columns of `A`.

The third step involves random numbers, so your result in steps 3–5 may be different.
``````% Step 1
[height,width] = size(A);``````
``````% Step 2
colIdxs = repmat(1:width,height,1);``````
``````% Step 3
R = rand(height,width);
[~,randomRowIdxs] = sort(R,1);``````
``````% Step 4
linearIdxs = sub2ind(size(A),randomRowIdxs,colIdxs);``````
``````% Step 5
resultExample1 = A(linearIdxs);``````

## Function

The function `shufflewithincols` encapsulates the procedure described above. It is properly documented and available for download here. The signature of the function is as follows:

``````function B = shufflewithincols(A)
end``````

To use `shufflewithincols`, pass a 2D matrix. The function will randomize the order of the elements within each column, and will store the result in the output argument.

The file ‘shufflewithincols.m’ must be in the current directory or in the MATLAB search path.
``````% Shuffle the elements within the columns of A
resultExample2 = shufflewithincols(A);``````

I recommend the following books to learn more on random numbers and matrix shuffling in MATLAB.

1. 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 elements within the columns of a 2D matrix in MATLAB. The source code developed in this tutorial is available at this page.