How can I isolate data from a matrix without a for loop?
古いコメントを表示
Dear all
given the matrix
M = rand(1000,10);
pre_indices = [ 40 60 70]
post_indices = [45 65 75]
I would like to isolate the following chunks from M
for i = 1:length(pre_indices)
M(pre_indices(i):post_indices(i),:)
end
could it be done without the loop? all chunks have the same dimensions
best regards MF
1 件のコメント
Guillaume
2017 年 9 月 15 日
It's debatable whether using accumarray or arrayfun and co. can be considered to be without a loop. Yes, it's not a for loop but all these functions mean more or less the same: "loop over the data and do the same thing to each element".
In your case, the loop may be the clearest and fastest way to obtain what you want.
回答 (2 件)
Andrei Bobrov
2017 年 9 月 15 日
編集済み: Andrei Bobrov
2017 年 9 月 15 日
M = (1:100)'*ones(1,5);
pre_indices = [ 40 60 70];
post_indices = [45 65 75];
n = (1:size(M,1))';
l = (n >= pre_indices(:)' & n <= post_indices(:)')*(1:numel(pre_indices))';
out = accumarray(l(l>0),n(l>0),[],@(x){M(x,:)});
or
n = (1:size(M,1))';
l = (n >= pre_indices(:)' & n <= post_indices(:)').*n;
out = M(l(l>0),:);
or
n = (1:size(M,1))';
l = any(n >= pre_indices(:)' & n <= post_indices(:)',2);
out = M(l,:);
if you have older version of MATLAB (< R2016b)
n = (1:size(M,1))';
k = bsxfun(@ge,n,pre_indices(:)') & bsxfun(@le,n,post_indices(:)');
l = k*(1:numel(pre_indices))';
out = accumarray(l(l>0),n(l>0),[],@(x){M(x,:)});
or
l = bsxfun(@times,k,n);
out = M(l(l>0),:);
or
out = M(any(k,2),:);
Guillaume
2017 年 9 月 15 日
arrayfun(@(si, ei) M(si:ei, :), pre_indices, post_indices, 'UniformOutput', false)
This is most likely slower than the explicit loop, and for all intents and purposes is a loop.
カテゴリ
ヘルプ センター および File Exchange で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!