How does the for-cycle check its conditions?
2 views (last 30 days)
Show older comments
Bálint Udvardy
on 30 Mar 2018
Answered: Jos (10584)
on 30 Mar 2018
I have a problem with using for cycle. Inside the cycle i want to decrease the maximum iteration for the cycle (see the code below).
for i=1:length(numL)% cell array
numL{i}=sortrows(numL{i},-1);
if size(numL{i},1)>1 % if the matrix inside the cell have more than one row
sz=size(numL{i},1);
for j=2:sz
if numL{1,i}(j-1,1)-numL{1,i}(j,1)<SideSize/2 %if the digits are close enough
numL{1,i}(j-1,5)=str2num(strcat(num2str(numL{1,i}(j,5)),num2str(numL{1,i}(j-1,5))));%merge digits
numL{1,i}(j,:)=[];%remove the row, where the second digit was
sz=sz-1;%decrement the value 'j' can have
end
end
end
numLL{i}=fliplr(numL{i}(:,5)');%store the vector of numbers into a new array
end

The problem happens in the 15. row (where there is a number 1 and 11). Basically, this is a post processing cycle after using OCR. In spite of decrementing the maximum value 'j' can have, it reaches 3 in case of a 'previously 3-row-matirx', but after merging the digits into one number, it should end... however, it does not. Or is the whole cycle wrong?
0 Comments
Accepted Answer
David Fletcher
on 30 Mar 2018
Edited: David Fletcher
on 30 Mar 2018
From the docs: Avoid assigning a value to the index variable within the loop statements. The for statement overrides any changes made to index within the loop.
Whilst you are not explicitly changing the loop variable, I suspect the end condition is set as the loop begins execution and will not recalculate on each iteration. If you need to vary the number of iterations of a loop then a while loop would be a better option.
0 Comments
More Answers (1)
Jos (10584)
on 30 Mar 2018
You cannot change the parameters of the for-loop within the counter, as demonstrated here:
a = 2 ; b = 6 ;
c = 0 ;
for k=a:b % executes b-a+1 = 5 times
c = c + 1 ;
disp([c k a b]) ;
a = 0 ; b = 0 ; k = 0 ;
disp([c k a b]) ;
end
To be flexible use a while loop:
k = 2 ; b = 6 ;
while k < b
k = k + 1
b = b - 1
end
or perhaps an if-break statement is an option:
for k=1:10
disp(k)
if k > 4
break
end
end
0 Comments
See Also
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!