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

116 views (last 30 days)
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 Comments
Jan
Jan on 15 Apr 2021
I do not know any programming language, which has an "if loop". Loops are built by for and while only (and GOTO...).

Sign in to comment.

Accepted Answer

Jan
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

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!