Split matrix into N Equal Parts by rows
古いコメントを表示
Hi,
I have an Nx10 matrix. How can I split this into three equally sized matrices (by number of rows) ? Is this something the reshape command can handle?
Thank you!
IP
採用された回答
その他の回答 (2 件)
Walter Roberson
2022 年 9 月 4 日
pieces = 3;
N = size(A, 1);
part_sizes = floor(N/pieces) * [1 1];
part_sizes(end+1) = N - sum(part_sizes);
C = mat2cell(A, part_sizes, size(A,2));
C is now a cell array in which the rows are equally divided as possible, with the last block being shorter if necessary.
2 件のコメント
Gorkem
2024 年 3 月 5 日
Thanks for the code. I was having trouble with the last block being too small compared to other blocks so I distributed residuals of the last block through the equally spaced blocks. It's not the best but here is the version I updated in this way:
pieces = 100;
N = size(A, 1);
part_sizes = floor(N/pieces) * [ones(1:pieces)];
Res = N - sum(part_sizes);
part_sizes(1:Res) = part_sizes(1:Res) + 1;
C = mat2cell(A, part_sizes, size(A,2));
AlexDiz
2024 年 8 月 16 日
it's [ones(1, pieces)] instead of [ones(1:pieces)]
but it works perfectly !
thanks
You can also use mat2tiles,
which doesn't require even multiples of the block size. However, it is never advisable to use cell arrays when you don't have to.
A=rand(14,6);
B=mat2tiles(A,[4,inf]) %group every 4 rows
カテゴリ
ヘルプ センター および File Exchange で Logical についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!