Any tips to updating 'for loop' index!

25 ビュー (過去 30 日間)
el-musleh
el-musleh 2020 年 1 月 4 日
コメント済み: el-musleh 2020 年 1 月 5 日
Hi, I have an issue while writing a code for a similar situation which is making the 'for loop' repeat again if the index variable updated its value within the loop! for instance, I want the 'for loop' for 'y' to repeat if a flag reach!
Any tips or best approach to implement it! Thanks!
check2nd_t=1;
for x=1:10
%some code
for y=1:10
%if abv(x) >= abb(y)
for z=1:10
if abv(x) > abc(z)
%done
break;
end
if y==10 & z==10 & check2nd_t ~=2 %is it && would make any change!?
check2nd_t=2;
y=1; %***my main point, I want the y loop to repaet again***
%some code
end
end
%some code
end
end

採用された回答

Walter Roberson
Walter Roberson 2020 年 1 月 5 日
check2nd_t=1;
for x=1:10
%some code
do_again = true;
while do_again
do_again = false;
for y=1:10
%if abv(x) >= abb(y)
for z=1:10
if abv(x) > abc(z)
%done
break;
end
if y==10 & z==10 & check2nd_t ~=2 %is it && would make any change!?
check2nd_t=2;
do_again = true;
break;
%***my main point, I want the y loop to repaet again***
%some code
end
end
if do_again; break; end
%some code
end
end
end
  1 件のコメント
el-musleh
el-musleh 2020 年 1 月 5 日
Thank you for highlighting this method, it leads me to fix the code and run smoothly! (I'd think of it!)

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

その他の回答 (1 件)

per isakson
per isakson 2020 年 1 月 4 日
編集済み: per isakson 2020 年 1 月 5 日
The documentation on for says:
Avoid assigning a value to the index variable within the loop statements. The for statement overrides any changes made to index within the loop.
The intention of your loop (from the first version of your question)
for x=1:10
if x==10
x=1;
end
end
may be implemented by
x = 1; % or maybe 0
while x <= 10
if x==10
x=1;
else
x = x + 1;
end
end
  3 件のコメント
Image Analyst
Image Analyst 2020 年 1 月 5 日
Which of the 3 for loops do you want to repeat? The x, y, or z loop? You should really be using while's instead of for's.
el-musleh
el-musleh 2020 年 1 月 5 日
I want to repeat the 'y' loop if z and y reach the end.
Yup, I'd used a while loop as well, thanks to Walter Roberson show a code explains it!
Thank you all!

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

カテゴリ

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