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

135 vues (au cours des 30 derniers jours)
Cside
Cside le 15 Avr 2021
Commenté : Cside le 16 Avr 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 commentaires
Jan
Jan le 15 Avr 2021
I do not know any programming language, which has an "if loop". Loops are built by for and while only (and GOTO...).
Cside
Cside le 15 Avr 2021
i meant ifelse condition/statement. Thank you!

Connectez-vous pour commenter.

Réponse acceptée

Jan
Jan le 15 Avr 2021
Modifié(e) : Jan le 15 Avr 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

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by