Can't exit a for loop correctly

조회 수: 4 (최근 30일)
Samuele Bolotta
Samuele Bolotta 2021년 4월 19일
답변: David Hill 2021년 4월 19일
I'm trying to find the baseline before a peak. So I wrote this for loop, which defines an index that starts from the index of the peak and decreases by 1 every time and therefore looks at the previous number in the vector to see if it's higher or lower than the current number. If the previous number is higher than the current number, then I want to define it as a baseline and break out of the loop.
rolling = 1:index_peak-1;
for num = rolling
idx = index_peak - num;
if ODv(idx-1) > ODv(idx)
baseline = ODv(idx);
break
end
end
However, what happens is that the for loop runs until a certain point, correctly finds the baseline, but then goes back to the start of the for loop and I see this error:
Array indices must be positive integers or logical values.
And in fact the index has suddenly become a completely different number.
Thanks!

답변 (1개)

David Hill
David Hill 2021년 4월 19일
for num = index_peak-1:-1:1
if ODv(num) > ODv(num+1)
baseline = ODv(num+1);
break;
end
end
Alternatively
baseline=ODv(find(diff(ODv(1:index_peak))<0,1,'last')+1);

카테고리

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