how to go backwards in a for loop until a condition is satisfied?
22 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponses (1)
Walter Roberson
le 21 Mar 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;
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!