For-loop in MATLAB

2 次查看(过去 30 天)
Margarida Chiote
Margarida Chiote 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