Search code examples
matlabmatrixmatrix-indexing

Reshaping a matrix in Matlab by selecting rows at a fixed distance


I have a matrix D in Matlab of dimension (a*b)xc with the following structure: suppose a=3, b=4, c=3

D=[1 1 10; 
   1 2 11; 
   1 3 17; 
   1 4 15; 
   2 1 68; 
   2 2 6; 
   2 3 15; 
   2 4 7; 
   3 1 5; 
   3 2 43; 
   3 3 0; 
   3 4 5];

The first column of D contains the numbers between 1 and a starting from 1 and increasing of 1 after b rows. The second column of D lists [1 2 ... b]' a-times.

I want to construct the matrix E of dimension (a*b)xc with the following structure

E=[1 1 10; 
   2 1 68; 
   3 1 5; 
   1 2 11;
   2 2 6; 
   3 2 43; 
   1 3 17; 
   2 3 15; 
   3 3 0; 
   1 4 15; 
   2 4 7; 
   3 4 5];

Solution

  • Maybe you simply want to sort the rows by the second column and are thinking too complicated:

    E = sortrows(D,2)