필터 지우기
필터 지우기

Skip multiple iterations in for loop

조회 수: 15 (최근 30일)
Nick
Nick 2011년 11월 3일
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

채택된 답변

Andrei Bobrov
Andrei Bobrov 2011년 11월 3일
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
Nick
Nick 2011년 11월 3일
Oh thanks, I ended up using some if statements as a workaround too but I think your code is a lot cleaner.
Matthew
Matthew 2011년 12월 6일
Nice solution, but it doesn't work if index=[0 0 0 0 1 0 0 1 0 0]

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

John Kitchin
John Kitchin 2011년 11월 5일
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 2011년 11월 3일
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
Jan
Jan 2011년 11월 3일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by