How to modify Loop variable inside the loop body

조회 수: 11 (최근 30일)
Vatsal Gupta
Vatsal Gupta 2018년 6월 30일
댓글: Douglas Anderson 2019년 1월 16일
for i=1:10
if randi(10)==3
i=i-1;
end
end
In the above code, i must get reduced by 1 whenever the if condition comes true. But it doesn't gets so. Any modifications so that loop variable i gets modified inside the loop body?

채택된 답변

Jan
Jan 2018년 6월 30일
This does not work in a for loop, but in while:
i = 1;
while i <= 10
disp(i)
...
i = i + 1;
if randi(10) == 3
i = i-1; % Or i - 2?
end
end
  댓글 수: 2
Vatsal Gupta
Vatsal Gupta 2018년 7월 1일
Thanks. I changed for into while and it worked :)
Douglas Anderson
Douglas Anderson 2019년 1월 16일
Thank you once again, Jan!

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

추가 답변 (0개)

카테고리

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

태그

제품


릴리스

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by