Splitting up a matrix - how can I do it more efficient?
Afficher commentaires plus anciens
Hi
Say I have a 200x8 matrix A. I want to split it up into (for instance) 10 parts, as follows:
[Rows 1-20 and all 8 columns, Rows 21-40 and all 8 columns, ..., Rows 181-200 and all 8 columns].
Let's write this as:
[20x8 submatrix 1, 20x8 sumatrix 2, ... , 20x8 submatrix 10]
in a next step, I want to concatenate all rows of each submatrix such that I get:
[160x1 submatrix 1, 160x1 submatrix2, ..., 160 submatrix 10]
The numbers are just examples of course. So currently, I do it like this:
nrSplits = 10; %split up original matrix into 10
nrColumns = 8;
A = randn(200,8);
y = 200:nrSplits;
for i = 1:nrSplits
foo = A(1+y*(i-1):y*i,1:nrColumns);
foo = foo(:);
ASplit(i,:) = foo;
end
..which works, but it seems to me a bit inefficient and clumsy. Is there a better way to do this? Maybe there are functions which would be helpful but I don't know of..?
Many thanks
Réponse acceptée
Plus de réponses (2)
Star Strider
le 29 Sep 2016
This works:
M = randi(99, 200, 8);
p = 20; % Partitions
Step1 = mat2cell(M, p*ones(1,size(M,1)/p), size(M,2));
Step2 = cellfun(@(x) x(:), Step1, 'UniformOutput',0);
James Tursa
le 29 Sep 2016
Modifié(e) : James Tursa
le 29 Sep 2016
This keeps the submatrices in column-order in memory as your example seems to do:
Asplit = reshape(permute(reshape(A',size(A,2),size(A,1)/nrSplits,[]),[2 1 3]),[],nrSplits);
If you really want the concatenation to be done row-by-row, that could be done too but the coding would be slightly different.
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!