MATLAB: How does the for-cycle check its conditions

decrease array rangeerrorfor cycleindex exceeds matrix dimensions

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?

Best Answer

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.