Filter löschen
Filter löschen

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

15 Ansichten (letzte 30 Tage)
EM geo
EM geo am 21 Mär. 2020
Kommentiert: Walter Roberson am 25 Mär. 2020
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

Antworten (1)

Walter Roberson
Walter Roberson am 21 Mär. 2020
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 Kommentare
EM geo
EM geo am 21 Mär. 2020
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 am 25 Mär. 2020
PS(K+1) = sum(YourTable.P(group_start_idx:K));

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by