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

回眸只為那壹抹淺笑 提交于 2019-12-05 06:55:12

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);

This is possible and is similar to the link you provided, but you need to decide how you want to divide up the 'leftover' rows when M mod 10 is not 0 and what you will do if there are fewer than 10 rows to begin with. The following should work if the listed assumptions are valid:

[M,N] = size(X);
Y = mat2cell(X, [repmat(ceil(M/10),[1 mod(M,10)]) ...
                 repmat(floor(M/10),[1 10-mod(M,10)])], N); 

Assumptions:

  1. You will have >= 10 rows (or you don't mind having 0xN arrays)
  2. You are content to have the additional rows divided among the first matrices - i.e. if you have 13 rows, then you have 3 consecutive matrices with 2 rows, followed by 7 matrices of 1 row.

For instance, I ran this on X = eye(7) and got:

Y = 
 [1x7 double]
   ...
 [1x7 double]
 [0x7 double]
 [0x7 double]
 [0x7 double]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!