In Matlab, I'm trying to transform a matrix A
to another matrix B
such that B
's columns are made up of square submatrices of A
. For example, if A
is:
A = [1 1 2 2
1 1 2 2
3 3 4 4
3 3 4 4];
I'd like B
to be:
B = [1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4]
A
could be, say 16-by-16, and constructing B
from 4-by-4 squares would result in B
being 4-by-64.
Is there an efficient way to do this using reshape
in combination with some other commands? Or some other approach? I am currently iterating in a loop, which is very slow with a large number of large source matrices.
Assume your matrix is a bit more general, and made of 3x2 blocks:
A = [1 1 2 2
1 1 2 2
1 1 2 2
3 3 4 4
3 3 4 4
3 3 4 4
5 5 6 6
5 5 6 6
5 5 6 6];
b = [3 2];
szA = size(A);
Transpose, reshape, permute, reshape.
nb = prod(szA./b); % Number of blocks
nelb = prod(b); % Number of elements per block
out1 = reshape(permute(reshape(A',szA(2),b(1),szA(1)/b(1)),[2,1,3]),nelb,nb)
Alternatively, slower and memory intensive but more readable:
d1 = repmat(b(1),1,szA(1)/b(1));
d2 = repmat(b(2),1,szA(2)/b(2));
out = reshape(mat2cell(A,d1,d2)',1,nelb);
out = reshape([out{:}],nelb,nb)
Now, if the blocks are square, simply set b = [2,2]
or b = [3,3]
, etc..., or simplify the general formulation removing indexing of b
and prod
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.