필터 지우기
필터 지우기

how to go backwards in a for loop until a condition is satisfied?

조회 수: 15 (최근 30일)
EM geo
EM geo 2020년 3월 21일
댓글: Walter Roberson 2020년 3월 25일
Hi everybody!
I'm working on a very long for loop in which i want also to go backwards in order to assess if a condition is satified. For example: suppose that the loop is arrived in position i = 16 (highlighted in grey). Now i want to go backwards in the vector Tm, using steps of 1 position, in order to assess if Tm <= -1. If yes, control the other value back to it, if is <-1 as well, control also the other one back to this last value. If is not <-1 then compute the sum of P of the corresponding positions of Tm <-1 (blue in figure) and place it in a new vector (example PS) at i = 16.
I hope my explanation is pretty clear.... !
Thanks in advance

답변 (1개)

Walter Roberson
Walter Roberson 2020년 3월 21일
You cannot do that in a single un-nested for loop.
You can do that with a single un-nested while loop in which you keep a state variable noting which direction you are going in order to figure out what you are trying to do at each iteration.
However, consider
group_start_idx = find(YourTable.tm(1:K-1) > -1, 1, 'last') + 1;
in which case you would process from group_start_idx:K . No loop is required.
If your table is quite big, then it might be worth restricting how far back you go. For example you might have reason to know that there are never more than 1023 negative locations to be grouped together; in that case you could restrict the search
search_from = max(1, K-1023);
group_start_idx = find(YoruTable.tm(search_from:K-1) > -1, 1, 'last') + search_from;
  댓글 수: 2
EM geo
EM geo 2020년 3월 21일
thank you for your reply @Walter Roberson! ok, but now what I should do with group_start_idx ini order to compute the sum of 209 + 183.5 (see the picture above, in blue circle) and place them in a new vector in position i = 16?
thank you veru much
Walter Roberson
Walter Roberson 2020년 3월 25일
PS(K+1) = sum(YourTable.P(group_start_idx:K));

댓글을 달려면 로그인하십시오.

카테고리

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