How can i skip iterations in for loop

26 ビュー (過去 30 日間)
Thomas
Thomas 2012 年 11 月 10 日
I need my loop to skip iterations to a given index. When i try it the obvious way like below
for i=2:1:(dim(1)-2)
%(a lot of irrelevant if statements)
%skip through points in the same hole
while graph(j) < tor
j=j+1;
end
if j < dim(1) - 2
i=j; % <== here is the problem
end
end
im getting a warning "LOOP index is changed inside of a FOR loop." and program ignores my iterator override.
How can i do this properly? or work around this?

採用された回答

Matt Fig
Matt Fig 2012 年 11 月 10 日
編集済み: Matt Fig 2012 年 11 月 10 日
Why not just give up on the FOR loop and use a WHILE loop? That way you control when to increment the index the whole time! As you have found out, MATLAB won't let manipulate the loop by changing the index inside.
idx = 1;
while idx<5
% Do stuff, check for idx condition, whatever..
if condition
idx = 1; % Reset idx! Or whatever....
else
idx = idx + 1; % Increment idx
end
end
  1 件のコメント
Thomas
Thomas 2012 年 11 月 10 日
guess the simplest solution is the hardest to find. thanks a lot!

サインインしてコメントする。

その他の回答 (1 件)

Matt J
Matt J 2012 年 11 月 10 日
編集済み: Matt J 2012 年 11 月 10 日
Use the CONTINUE command
if i~=j
continue;
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by