how to avoid for loop
조회 수: 5 (최근 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!