how to avoid for loop

조회 수: 1 (최근 30일)
sb
sb 2019년 11월 7일
댓글: Image Analyst 2019년 11월 7일
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

채택된 답변

Jan
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
sb
sb 2019년 11월 7일
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
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
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)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by