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

226 views (last 30 days)
Cside on 15 Apr 2021
Commented: Cside on 16 Apr 2021
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 CommentsShowHide 1 older comment
Cside on 15 Apr 2021
i meant ifelse condition/statement. Thank you!

Jan on 15 Apr 2021
Edited: Jan on 15 Apr 2021
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
Cside on 16 Apr 2021
Thank you so much, i managed to debug it