Exiting if condition when condition is not met, but continue for loop

조회 수: 91 (최근 30일)
Cside
Cside 2021년 4월 15일
댓글: Cside 2021년 4월 16일
Hi I have a if condition nested in a for loop that looks something like this. So there will be times when sum(A) does not meet the condition and the error will appear. However, I want the for loop to still loop the next iteration, ie if condition is not met at 6th loop, error should be displayed and the for loop moves on to the 7th one.
I tried the continue function, but it does not prompt the for loop to continue when condition is not met. Which function is recommended in this case/how can the code be improved?
Many thanks!
for k = 1:10
code
if sum(A)> 10
code
else
disp(error)
continue
end
code
end
  댓글 수: 2
Jan
Jan 2021년 4월 15일
I do not know any programming language, which has an "if loop". Loops are built by for and while only (and GOTO...).
Cside
Cside 2021년 4월 15일
i meant ifelse condition/statement. Thank you!

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

채택된 답변

Jan
Jan 2021년 4월 15일
편집: Jan 2021년 4월 15일
The continue statement does proceed the loop, exactly as you have described your needs. Why do you think, that "it does not prompt the for loop to continue"?
for k = 1:7
fprintf('\nk=%d:', k)
if mod(k, 3) == 0
fprintf(' mod(%d,3)=0 ', k)
else
fprintf(' Not matching')
continue
end
fprintf(' final part\n')
end
k=1:
Not matching
k=2:
Not matching
k=3:
mod(3,3)=0
final part
k=4:
Not matching
k=5:
Not matching
k=6:
mod(6,3)=0
final part
k=7:
Not matching
A nicer version:
for k = 1:7
fprintf('\nk=%d:', k)
if mod(k, 3) ~= 0
fprintf(' Not matching')
continue
end
fprintf(' mod(%d,3)=0 ', k)
fprintf(' final part\n')
end
or
for k = 1:7
fprintf('\nk=%d:', k)
if mod(k, 3) == 0
fprintf(' mod(%d,3)=0 ', k)
fprintf(' final part\n')
else
fprintf(' Not matching')
% No CONTINUE needed here
end
end

추가 답변 (0개)

카테고리

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