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

조회 수: 1 (최근 30일)
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!

채택된 답변

Bjorn Gustavsson
Bjorn Gustavsson 2020년 7월 8일
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
Arielle Patapanian
Arielle Patapanian 2020년 7월 8일
Thanks, I got it to work by changing the outer loop from a for loop to a while loop like you suggested!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2020년 7월 8일

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by