フィルターのクリア

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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by