Splitting up a matrix - how can I do it more efficient?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
MiauMiau
am 29 Sep. 2016
Bearbeitet: James Tursa
am 29 Sep. 2016
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
0 Kommentare
Akzeptierte Antwort
Massimo Zanetti
am 29 Sep. 2016
Bearbeitet: Massimo Zanetti
am 29 Sep. 2016
This will do your work efficiently.
%matrix size
n = 200;
m = 8;
%number of rows to cut
t = 20;
%generate matrix
A = randi(10,n,m);
%operate matrix manipulation programmatically
S = 1:t:n;
E = arrayfun( @(k) reshape(A(k:k+t-1,:),t*m,1) , S , 'UniformOutput', false );
E = cell2mat(E);
You can also change the parameters n,m,t.
0 Kommentare
Weitere Antworten (2)
Star Strider
am 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);
0 Kommentare
James Tursa
am 29 Sep. 2016
Bearbeitet: James Tursa
am 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.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!