For-loop in MATLAB
3 ビュー (過去 30 日間)
古いコメントを表示
I have a vector ( Corr_vector) i made a loop that runs the variable i 44 in 44 points and verifies if the value R=50 belongs to [x,y]. I ran this code and realized that it doesn't execute the break command and prints all the xand y values until the end. I only want to perform this loop until the conditions R>=x & R<=y are verified.
for i = 1:length(Corr_vector)
x=i;
y=i+44;
if R>=x & R<=y
disp(x);
disp(y);
break
else
i=i+44;
continue
end
end
0 件のコメント
回答 (2 件)
James Tursa
2020 年 6 月 11 日
編集済み: James Tursa
2020 年 6 月 11 日
You should not modify the index variable i inside the loop:
for i = 1:length(Corr_vector)
:
i=i+44; % this is bad program design, you should not modify i inside the loop
You should change your logic to avoid this practice.
0 件のコメント
Walter Roberson
2020 年 6 月 11 日
Your code is equivalent to
Hidden_internal_upper_bound = length(Corr_vector);
if Hidden_internal_upper_bound < 1
i = [];
else
Hidden_internal_i = 0;
while true
if Hidden_internal_i >= Hidden_internal_upper_bound
break;
end
Hidden_internal_i = Hidden_internal_i + 1;
i = Hidden_internal_i;
x = i;
y = i+44;
if R>=x & R<=y
disp(x);
disp(y);
break
else
i = i+44;
continue
end
end
end
Notice that each time through, the i that you changed using i = i+44 gets replaced with the hidden internal loop variable.
You cannot escape from an outer for loop by changing the loop control variable to be out of range! Changes to loop control variables are erased as soon as the next iteration of the loop starts. The only time that a change to a loop control variable is not discarded is the case where there would be no more iterations of the loop.
0 件のコメント
参考
カテゴリ
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!