Split matrix into N Equal Parts by rows
Afficher commentaires plus anciens
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
Réponse acceptée
Plus de réponses (2)
Walter Roberson
le 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 commentaires
Gorkem
le 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
le 16 Août 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
Catégories
En savoir plus sur Logical dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!