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

1 visualización (últimos 30 días)
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!

Respuesta aceptada

Bjorn Gustavsson
Bjorn Gustavsson el 8 de Jul. de 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
  1 comentario
Arielle Patapanian
Arielle Patapanian el 8 de Jul. de 2020
Thanks, I got it to work by changing the outer loop from a for loop to a while loop like you suggested!

Iniciar sesión para comentar.

Más respuestas (1)

Walter Roberson
Walter Roberson el 8 de Jul. de 2020

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by