How does the for-cycle check its conditions?
Show older comments
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?
Accepted Answer
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
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!