2

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];
Divakar
  • 218,885
  • 19
  • 262
  • 358
TEX
  • 2,249
  • 20
  • 43

2 Answers2

2

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

E = sortrows(D,2)
SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
Nras
  • 4,251
  • 3
  • 25
  • 37
1

For a general case when the input data is not already sorted, an approach based on reshape and permute would be suited -

E = reshape(permute(reshape(D,b,size(D,1)/b,[]),[2 1 3]),size(D))
Divakar
  • 218,885
  • 19
  • 262
  • 358