2017-07-19 123 views
-1

我有一个程序,所有的功能都在for循环中。如果条件成立,我想跳过一些变量以避免做任何事情。例如:如何跳过for循环的一些迭代并在Matlab中执行其他迭代?

for i=1:a 

     for j=1:b 
     if counter=101 
     %until i<21 do nothing then if i=21 continue the loop and do what I want 
     % until i=23, after that again i goes forward but don't do any thing 
     %until i=44 again do the progress and continue the loop. 
     end 


     %do what I want 

     end 

    end 

但我无法得到正确的答案。 我把它写下来一样:

if counter==101 
      j=1; 
      while (i < a/3+1) 
       i=i+1; 
       continue 
      end 
     end 
     if counter==201 
      j=1; 
      while (i < 2*a/3+1) 
       i=i+1; 
       continue 
      end 
     end 

在这段代码中,I = 21后的循环重复做,之后,在我去号码前21(例如3),但我不希望它。 如果有人有建议,将不胜感激。

+0

请更正代码的层次结构 – OmG

回答

3

这种情况应该是你在找什么:

for i=1:a 
     for j=1:b 
      if i < 21 || (i >= 23 && i < 44) 
       % Skip loop before 21 and between 23 and 43 
       continue 
      end 
      if counter == 101 
       % Do stuff 
      end 
     end 

end 

至少有在你的代码中的错误:if counter=101是不是一个有效的比较,你是分配值101来对抗。你应该使用if counter==101 此外,我不明白你的第二块代码。至少,在给它赋值之前使用i,并且可能会丢失外部循环。

编辑: 话虽这么说,你可能想简单地调整你的循环变量:

range = [1:20 , 22, 44:a]; 
for i = range 
    % Do stuff 
end