필터 지우기
필터 지우기

Change a for loop iteration if condition is met

조회 수: 12 (최근 30일)
Richard Wolvers
Richard Wolvers 2017년 6월 18일
답변: Julian Hapke 2017년 6월 20일
Hello everyone,
I have the following problem. I want to stop an iteration in a for loop if a certain condition is met and then let the iteration continue from another value (in other words, skip certain iterations). In the below example the end values should be: b=20 and c=0. (Because the iteration goes to 50, the elseif condition wil never be met). How can i do this?
a= 5;
b=0;
c=0;
for t=1:100
a = a+t
if a == 20
b = 20;
% then the iteration should stop and start from t=50
elseif a == 30
c = 20;
% Then the iteration should stop and start from t=70
end
end
  댓글 수: 2
dpb
dpb 2017년 6월 18일
That's inconsistent problem statement; a can never be anything between 20 and 70 because when t becomes 50 the sum immediately passes 30.
Need to write the specification more precisely first, then if it can actually be met as not logically inconsistent, use of a while loop with computed t value instead of counted for will probably be the solution.
Sagar Doshi
Sagar Doshi 2017년 6월 20일
You can use break in your loop as mentioned in the documentation link here to come out of the loop and have another loop to start with required value for 'a' and 't'.

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

답변 (1개)

Julian Hapke
Julian Hapke 2017년 6월 20일
with a while loop:
a=5;
b=0;
c=0;
t = 1;
while t <=100
a = a+t;
if a == 20
b = 20;
t = 50;
elseif a == 30
c = 20;
t = 70;
else
t = t+1;
end
end
but have in mind, that this is nonsense, as dpb pointed out.

카테고리

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