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 comentario

Guillaume
Guillaume el 15 de Sept. de 2017
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.

Iniciar sesión para comentar.

Respuestas (2)

Andrei Bobrov
Andrei Bobrov el 15 de Sept. de 2017
Editada: Andrei Bobrov el 15 de Sept. de 2017
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 el 15 de Sept. de 2017
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.

Categorías

Más información sobre Matrices and Arrays en Centro de ayuda y File Exchange.

Preguntada:

el 15 de Sept. de 2017

Editada:

el 15 de Sept. de 2017

Community Treasure Hunt

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

Start Hunting!

Translated by