How can I divide a matrix into unequally-sized submatrices?

C. Reed picture C. Reed · Dec 28, 2010 · Viewed 7.1k times · Source

I am wondering if it is possible to use the mat2cell function to divide an MxN matrix into 10 submatrices with the same column size, N, and approximately the same row size ~M/10? If mod(M, 10) == 0 then all submatrices will have the same size, otherwise a few matrices will have +/-1 row. Is this possible via the mat2cell function?

For reference, if the row sizes are all the same it's fairly straightforward, as explained here:
How to divide a matrix into equals parts?

Answer

gnovice picture gnovice · Dec 29, 2010

Here's a simple solution using the functions linspace, round, and diff:

[M, N] = size(mat);  % Matrix size
nSub = 10;           % Number of submatrices
cMat = mat2cell(mat, diff(round(linspace(0, M, nSub+1))), N);

This approach will distribute extra rows in a more uniform fashion across the resulting cells of the cell array. Note these outputs that you will get when applying the above using mat = magic(5); (left) and mat = magic(13); (right):

cMat =              cMat = 

    [1x5 double]        [1x13 double]
    [0x5 double]        [2x13 double]
    [1x5 double]        [1x13 double]
    [0x5 double]        [1x13 double]
    [1x5 double]        [2x13 double]
    [0x5 double]        [1x13 double]
    [1x5 double]        [1x13 double]
    [0x5 double]        [1x13 double]
    [1x5 double]        [2x13 double]
    [0x5 double]        [1x13 double]

If you'd prefer a random distribution of extra rows, you can use randperm like so:

subSizes = diff(round(linspace(0, M, nSub+1)));
cMat = mat2cell(mat, subSizes(randperm(nSub)), N);