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

1 次查看(过去 30 天)
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!

采纳的回答

Azzi Abdelmalek
Azzi Abdelmalek 2014-1-3
编辑:Azzi Abdelmalek 2014-1-3
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(:,:)'

更多回答(2 个)

Andrei Bobrov
Andrei Bobrov 2014-1-6
编辑:Andrei Bobrov 2014-1-6
a1 = cat(1,A1,A2,A3);
t = rem(0:size(a1,1)-1,4)+1 <= 2;
out = [a1(t,:);a1(~t,:)];
or in one row
out = reshape(permute(reshape(cat(1,A1,A2,A3),2,2,3,[]),[1 3 2 4]),[],2);

Jos (10584)
Jos (10584) 2014-1-6
You can use some clever indexing:
A1 = cumsum(ones(4,2)), A2 = A1 + 4, A3 = A1 + 8 % as above
n = 2 ;
% engine
m = size(A1,1) ; % all the same
% build a clever sorting matrix IX
IX = repmat([1+floor((0:m-1)/n) ; zeros(1,m) ; 1:m].', 3, 1)
IX(:,2) = 1+floor((0:(3*m)-1)/m)
% col 1 : selection order based on n
% col 2 : which matrix (A1, A2 or A3),
% col 3 : which element inside matrix
% sort them nicely
[IXsorted,SI] = sortrows(IX)
B = [A1 ; A2 ; A3]
B = B(SI,:)

类别

Help CenterFile Exchange 中查找有关 Operators and Elementary Operations 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by