Split matrix into N Equal Parts by rows
Show older comments
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
Accepted Answer
More Answers (2)
Walter Roberson
on 4 Sep 2022
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 Comments
Gorkem
on 5 Mar 2024
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
on 16 Aug 2024
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
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!