Skip multiple iterations in for loop

12 views (last 30 days)
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

Accepted Answer

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

Sign in to comment.

More Answers (2)

John Kitchin
John Kitchin on 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 on 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 Comment
Jan
Jan on 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.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!