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

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
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
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에 대해 자세히 알아보기

질문:

2017년 9월 15일

편집:

2017년 9월 15일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by