MATLAB Answers

how to avoid for loop

3 views (last 30 days)
sb on 7 Nov 2019
Commented: Image Analyst on 7 Nov 2019
can this 'for loop' be replaced? thanks in advance
for i=1 : length(b)-1
c=length(tof( tof >= b(i) & tof < b(i+1)) ) ;

Accepted Answer

Jan on 7 Nov 2019
Edited: Jan on 7 Nov 2019
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));
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.
Image Analyst
Image Analyst on 7 Nov 2019
Not sure what that means exactly, but if you need more help, attach your data and the desired/expected output.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 7 Nov 2019
Try this (untested)
lastIndex = length(b)-1;
indexes = (tof > b(1:lastIndex)) & (tof < b(2:lastIndex + 1));
counts = cumsum(indexes)


Community Treasure Hunt

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

Start Hunting!