Splitting up a matrix - how can I do it more efficient?
1 回表示 (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Massimo Zanetti
2016 年 9 月 29 日
編集済み: Massimo Zanetti
2016 年 9 月 29 日
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 件のコメント
その他の回答 (2 件)
Star Strider
2016 年 9 月 29 日
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 件のコメント
James Tursa
2016 年 9 月 29 日
編集済み: James Tursa
2016 年 9 月 29 日
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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!