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

133 visualizaciones (últimos 30 días)
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 comentarios
Jan
Jan el 15 de Abr. de 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 el 15 de Abr. de 2021
i meant ifelse condition/statement. Thank you!

Iniciar sesión para comentar.

Respuesta aceptada

Jan
Jan el 15 de Abr. de 2021
Editada: Jan el 15 de Abr. de 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

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by