How to Keep Nested For Loop Indexes From Equaling Each Other

1 vue (au cours des 30 derniers jours)
Thomas Schoenstein
Thomas Schoenstein le 5 Mai 2020
Commenté : Stephen23 le 5 Mai 2020
If I have two nested for loops like this, is there a way to skip the iteration where i=j?
for i=1:50
for j=1:50
code
end
end

Réponse acceptée

Jason Nicholson
Jason Nicholson le 5 Mai 2020
Modifié(e) : Jason Nicholson le 5 Mai 2020
Use the continue keyword.
for i=1:50
for j=1:50
if j==i
continue; % breaks the inner for loop at the current iteration
else
% Do stuff here
fprintf('i=%d, j=%d\n',i,j);
end
end
end
If this response answers your question, please click "accept this answer."
  2 commentaires
Thomas Schoenstein
Thomas Schoenstein le 5 Mai 2020
Thank you!
Stephen23
Stephen23 le 5 Mai 2020
for i=1:50
for j=1:50
if j~=i
...
end
end
end

Connectez-vous pour commenter.

Plus de réponses (2)

Walter Roberson
Walter Roberson le 5 Mai 2020
for i=1:50
for j=[1:i-1,i+1:50]
or
for i=1:50
for j=setdiff(1:50, i)

per isakson
per isakson le 5 Mai 2020
for ii=1:50
for jj=1:50
if not(jj==ii)
code
end
end
end

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