How does the for-cycle check its conditions?
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Bálint Udvardy
il 30 Mar 2018
Risposto: Jos (10584)
il 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 Commenti
Risposta accettata
David Fletcher
il 30 Mar 2018
Modificato: David Fletcher
il 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 Commenti
Più risposte (1)
Jos (10584)
il 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 Commenti
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!