Code initiates again after exiting while loop which is within an if statement

1 view (last 30 days)
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!

Accepted Answer

Bjorn Gustavsson
Bjorn Gustavsson on 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

More Answers (1)

Walter Roberson
Walter Roberson on 8 Jul 2020

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!