MATLAB Answers

0

how to avoid for loop

Asked by surjendu on 7 Nov 2019
Latest activity Commented on by Image Analyst
on 7 Nov 2019
Accepted Answer by Jan
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 Comments

Sign in to comment.

Tags

2 Answers

Jan
Answer by Jan
on 7 Nov 2019
Edited by Jan
on 7 Nov 2019
 Accepted Answer

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 Comments

surjendu on 7 Nov 2019
this loop works well and is 1.5 times faster. tof is a scaler, b is sorted, I am looking at histcouts without matlab's inbuilt code.
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.


Image Analyst
Answer by 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)

  0 Comments

Sign in to comment.