For-loop in MATLAB

1 view (last 30 days)
Margarida Chiote
Margarida Chiote on 11 Jun 2020
Answered: Walter Roberson on 11 Jun 2020
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

Answers (2)

James Tursa
James Tursa on 11 Jun 2020
Edited: James Tursa on 11 Jun 2020
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 on 11 Jun 2020
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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!