如何将矩阵划分为大小不相等的子矩阵? [英] How can I divide a matrix into unequally-sized submatrices?
问题描述
我想知道是否可以使用mat2cell
函数将MxN
矩阵划分为具有相同列大小N
和大约相同行大小~M/10
的10个子矩阵?如果mod(M, 10) == 0
,则所有子矩阵都将具有相同的大小,否则,一些矩阵将具有+/- 1行.通过mat2cell
函数可以做到这一点吗?
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?
推荐答案
这是使用 linspace
, round
和 diff
:
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);
此方法将以更统一的方式在单元阵列的结果单元之间分配额外的行.请注意使用mat = magic(5);
(左)和mat = magic(13);
(右)应用上述方法时将获得的这些输出:
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]
如果您希望随机分配多余的行,可以使用 randperm
像这样:
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);
这篇关于如何将矩阵划分为大小不相等的子矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!