Skip multiple iterations in for loop
22 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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 个评论
更多回答(2 个)
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
0 个评论
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
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 Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!