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

22 次查看(过去 30 天)
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

请先登录,再进行评论。

类别

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