arraysmatlabrow-major-ordercolumn-major-order

In MATLAB, for a 2D array how do I get an index that will iterate the other dimension first


I've got an algorithm that fills a 2x3 subplot array using a single index i=1:6.

According to the documentation,

subplot(m,n,p) divides the current figure into an m-by-n grid and creates an axes for a subplot in the position specified by p. MATLAB® numbers its subplots by row, such that the first subplot is the first column of the first row, the second subplot is the second column of the first row, and so on.

So when iterating over a 2x3 subplot array using i=1:6, would result in the following row-major order:

+---+---+---+
| 1 | 2 | 3 |
| 4 | 5 | 6 |
+---+---+---+

If I want fill the subplots in column-major order, I would have to convert my index 1 2 3 4 5 6 to 1 4 2 5 3 6.

How can I do this?


Solution

  • You can just create a 2D array of indices that is 3 x 2, transpose it to be 2 x 3 and then column-major has become row-major relative to the initial matrix.

    indices = reshape(1:6, [], 2).';
    

    Then you can create your subplots by looping through these indices

    for k = 1:numel(indices)
        subplot(2, 3, indices(k))
    end