Code initiates again after exiting while loop which is within an if statement
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Arielle Patapanian
am 8 Jul. 2020
Kommentiert: Arielle Patapanian
am 8 Jul. 2020
i = 2
for i = 2:523
if Storage(i-1) >= Stage_1_trigger
Outflow = Demand_and_losses
if Storage(i-1) + Flow(i) - Outflow < 0
Storage(i) = 0
elseif Storage(i-1) + Flow(i) - Outflow > Initial_storage
Storage(i) = Initial_storage
else
Storage(i) = Storage(i-1) + Flow(i) - Outflow
end
Storage(i)
i = i + 1
else
while Storage(i-1)<= Stage_1_exit
Outflow = 0.9*Demand_and_losses
if Storage(i-1) + Flow(i) - Outflow < 0
Storage(i) = 0
elseif Storage(i-1) + Flow(i) - Outflow > Initial_storage
Storage(i) = Initial_storage
else
Storage(i) = Storage(i-1) + Flow(i) - Outflow
end
i = i + 1
end
end
end
Hi, I have this code above. However, when the code exits the while loop, the i value initiates again.
For example, before entering the while loop, i = 5. When exiting the while loop, i = 10. However, when the code finishes with the while loop and goes back to the first for loop, i = 5 again rather than 10. How can I prevent this? Thanks!
0 Kommentare
Akzeptierte Antwort
Bjorn Gustavsson
am 8 Jul. 2020
In your outer for-loop you use you use i as loop-index. The way matlab has implemented things this is done (IIRC) such that there will be an array with loop-index-values that the loop-variable will step through. This has precedence, so this differs from for example C where the loop simply increments until the interrupt-condition. You might have to code this differently.
First time you fall into the while-loop you will start with some value of i, lest say 5, it will be incremented to 10, then next time through the for-loop i will be set to the next value of the index-array, i.e. 6, and then proceed with that.
The simplest way to implement this snippet to behave in the C-way might be to change the outer for-loop to a while-loop and just make sure the incrementing of i behaves as you want.
HTH
Weitere Antworten (1)
Walter Roberson
am 8 Jul. 2020
I gave a detailed explanation of how for loops work in https://www.mathworks.com/matlabcentral/answers/356884-how-do-i-convert-this-for-loop-into-a-while-loop#answer_281739
Siehe auch
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!