arraysmatlabmatrixvectorization

How to divide a matrix in MATLAB into N^2 segments each with NxN elements?


Assuming we have a matrix M of size N^2 x N^2 elements (e.g., 9x9), what's the fastest way to split it into say 3x3 segments (each with 3x3 elements).

One way that comes to mind is the following:

M = magic(9);
N = 3; 

m = mat2cell(M, N * ones(1, size(M, 1) / N), ...
                N * ones(1, size(M, 2) / N));

I, however, do not prefer the use of cells. I was curious if there is a way to split the matrix and store the segments in the form of a 3D matrix using a column-major indexing for the segments (e.g., the first segment m{1} becomes m(:, :, 1) and the second segment m{2} becomes m(:, :, 2), and so on).


Solution

  • You can combine reshape with permute, e.g. like so:

    reshape(permute(reshape(M, N,N,N,N), [1,3, 2,4]), N,N, N*N)
    

    The inner reshape has your intended "cells" split into dimensions 1 and 3, which permute shifts into dimensions 1 and 2. The outer reshape may be omitted, if you are ok with having a 4D matrix.