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!