Effacer les filtres
Effacer les filtres

Skip multiple iterations in for loop

15 vues (au cours des 30 derniers jours)
Nick
Nick le 3 Nov 2011
Is there a way to adjust the "continue" keyword in Matlab so that it skips multiple iterations? For example can I do this?
index=[0 0 0 1 0 0 0 0 0 0];
a=0;
for i=1:10
if index(i)==1
continue ("skip next 3 iterations")
end
a=a+1
end
so what I would end up is something like a = 1, 2, 3, 4, 5, 6, 7

Réponse acceptée

Andrei Bobrov
Andrei Bobrov le 3 Nov 2011
index=[0 0 0 0 1 0 0 0 0 0];
a=[];
b = 1;
for i=1:10
if index(i)==1
if i==1 || index(i-1)==0
index(i+[0:2])=1;
end
continue
end
a=[a b];
b = b+1;
end
ADD (11:46 MDT 06.12.2011) for reply Matthew (Thank you Matthew!)
1. with loop for..end and continue
a = [];
b = 1;
for i1=1:numel(index)
if index(i1)==1
k = 1;
end
if k <= 3
k = k + 1;
continue
end
a=[a b];
b = b+1;
end
2. without loop
a = 1:numel(setdiff(1:numel(index),unique(bsxfun(@plus,find(index),(0:2)'))))
  2 commentaires
Nick
Nick le 3 Nov 2011
Oh thanks, I ended up using some if statements as a workaround too but I think your code is a lot cleaner.
Matthew
Matthew le 6 Déc 2011
Nice solution, but it doesn't work if index=[0 0 0 0 1 0 0 1 0 0]

Connectez-vous pour commenter.

Plus de réponses (2)

John Kitchin
John Kitchin le 5 Nov 2011
This looks like it will do what you want:
index=[0 0 0 1 0 0 0 0 0 0];
a=0;
i = 1;
while i < length(index)
if index(i) == 1
i = i+3;
else
i = i+1;
end
a = a + 1
end

Image Analyst
Image Analyst le 3 Nov 2011
You can do what (I think) you want if you do it like this:
a = 0;
indexesToUse = find(index);
for k = indexesToUse
fprintf('k = %d\n', k);
a = a + 1;
end
This would do the loop only for locations where your "index" array was equal to 1. Is that what you're after?
  1 commentaire
Jan
Jan le 3 Nov 2011
The JIT has some magic power:
a = 0; indexesToUse = logical([0,1,0,1,0]);
for k = 1:n, if indexesToUse(k), <operations>, end, end
This is faster under some conditions.

Connectez-vous pour commenter.

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