Azzera filtri
Azzera filtri

Skip multiple iterations in for loop

13 visualizzazioni (ultimi 30 giorni)
Nick
Nick il 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

Risposta accettata

Andrei Bobrov
Andrei Bobrov il 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 Commenti
Nick
Nick il 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 il 6 Dic 2011
Nice solution, but it doesn't work if index=[0 0 0 0 1 0 0 1 0 0]

Accedi per commentare.

Più risposte (2)

John Kitchin
John Kitchin il 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 il 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 Commento
Jan
Jan il 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.

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by