MATLAB: Rearrange 3 small matrices to a bigger one with a certain order: taking first n-rows of each of the smaller matrices after each other

efficientindexindicesmatrixmatrix manipulationrearrangerowswapunit matrix

I have three smaller Matrices that I want to transform to one bigger one with the following order:
>> A1 =
1 1
2 2
3 3
4 4
A2 =
5 5
6 6
7 7
8 8
A3 =
9 9
10 10
11 11
12 12
They should be transformed to one Matrix in this order:
B =
1 1
2 2
5 5
6 6
9 9
10 10
3 3
4 4
7 7
8 8
11 11
12 12
So always take the first n-rows of each matrix (here n=2, in the actual case 'n' ist way higher), then take all the second "packages" and so on (In this case: Take first two lines of each Matrix, then take lines 3-4 of each matrix, then lines 5-6 of each matrix and so on)
Is there a nice and quick solution that does not require loops? Maybe using reshape or some functions to swap lines or using indices or so..?
Thanks in advance again!

Best Answer

  • m=size(A1,2);
    n=2
    A11=permute(reshape(A1',m,n,[]),[2 1 3]);
    A22=permute(reshape(A2',m,n,[]),[2 1 3]);
    A33=permute(reshape(A3',m,n,[]),[2 1 3]);
    A=permute([A11;A22;A33],[2 1 3]);
    B=A(:,:)'