Reputation: 47
I have a k * MxN cell array that I want to reshape into a M x k * N array. But I want to do this blockwise so that the row structure is preserved.
A B C --> A B C G H I M N O
D E F D E F J K L P Q R
G H I
J K L
M N O
P Q R
Is there a possibility without any loops?
Upvotes: 1
Views: 553
Reputation: 112659
This can be done with a combination of reshape
and permute
. This approach works for numeric arrays or for cell arrays.
Let A
denote your array. Then, the desired result is
B = reshape(permute(reshape(A.',N,M,[]),[2 1 3]),M,[]);
Or, as noted by Divakar, you can save the transpose, which will reduce running time:
B = reshape(permute(reshape(A,M,k,[]),[1 3 2]),M,[]);
For example,
A = [ 5 9 2
5 8 4
5 0 4
5 5 7
7 6 3
8 5 0
8 7 5
3 0 5 ];
M = 2;
N = size(A,2);
k = size(A,1)/M;
gives
B =
5 9 2 5 0 4 7 6 3 8 7 5
5 8 4 5 5 7 8 5 0 3 0 5
Upvotes: 2
Reputation: 8459
If you matrix is small, then this should work,
cell2mat(arrayfun(@(i) A(2*i-1:2*i,:),1:3,'UniformOutput',0))
however performance may be better with a more simple loop, especially for a larger matrix.
Upvotes: 0