how to avoid for loop
1 回表示 (過去 30 日間)
古いコメントを表示
can this 'for loop' be replaced? thanks in advance
counts=[];
for i=1 : length(b)-1
c=length(tof( tof >= b(i) & tof < b(i+1)) ) ;
counts=[counts,c];
end
0 件のコメント
採用された回答
Jan
2019 年 11 月 7 日
編集済み: Jan
2019 年 11 月 7 日
A ,ore efficient version of the loop:
nb = numel(b) - 1;
counts = zeros(1, nb); % Pre-allocation!!!
for i = 1:nb
counts(i) = sum(tof >= b(i) & tof < b(i+1));
end
Is tof a scalar or a vector? Is b sorted? Are you looking for histcounts ?
Pre-allocation is essential, because letting an array grow iteratively is extremely expensive.
2 件のコメント
Image Analyst
2019 年 11 月 7 日
Not sure what that means exactly, but if you need more help, attach your data and the desired/expected output.
その他の回答 (1 件)
Image Analyst
2019 年 11 月 7 日
Try this (untested)
lastIndex = length(b)-1;
indexes = (tof > b(1:lastIndex)) & (tof < b(2:lastIndex + 1));
counts = cumsum(indexes)
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!