For loop to split matrix to equal sized sub-matrices

Well, I know that the poster explicitly asked for a for loop, and Jeff Mather’s answer provided exactly that.

But still I got curious whether it is possible to decompose a matrix into tiles (sub-matrices) of a given size without a loop. In case someone else is curious, too, here’s what I have come up with:

T = permute(reshape(permute(reshape(A, size(A, 1), n, []), [2 1 3]), n, m, []), [2 1 3])

transforms a two-dimensional array A into a three-dimensional array T, where each 2d slice T(:, :, i) is one of the tiles of size m x n. The third index enumerates the tiles in standard Matlab linearized order, tile rows first.

The variant

T = permute(reshape(A, size(A, 1), n, []), [2 1 3]);
T = permute(reshape(T, n, m, [], size(T, 3)), [2 1 3 4]);

makes T a four-dimensional array where T(:, :, i, j) gives the 2d slice with tile indices i, j.

Coming up with these expressions feels a bit like solving a sliding puzzle. 😉

Leave a Comment