For-loop in MATLAB

조회 수: 2 (최근 30일)
Margarida Chiote
Margarida Chiote 2020년 6월 11일
답변: Walter Roberson 2020년 6월 11일
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

답변 (2개)

James Tursa
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.

Walter Roberson
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by