MATLAB: Evaluation of a for loop

for loop

hello
is this pseudo code:
for Counter=1:size(M,2)
if someting
delete row from M
end
end
If would expect that if the size of M changing the range of Counter would change do but that does not happen, instead Counter will rang from 1 to the begin size of M
so size(M,2) is not evaluated each time that the loop runs?
I notices with while …end you do not have the problem or am I completely mistaken?
thanks for any insights
regards,Jürgen

Best Answer

The bounds and increments of "for" loops are recorded at the time the "for" statement is executed, and changes to any of the bounds or increment in the body of the loop do not have any effect on the execution of the loop. If you need to have the bounds vary, use a "while" loop.
In the particular case of deleting elements of the array, a "forward" for loop is not appropriate. Suppose Counter is 3 and you delete element 3, then what was in element 4 "falls down" to occupy element 3, so in order to test that element to see if it should be deleted, you would have to re-test at location 3 rather than proceeding on to location 4.
One of the tricks for avoiding this problem is to run the "for" loop backwards:
for Counter = size(M,1) : -1 : 1
if someting
delete row from M
end
end
Note here I adjusted to size(M,1) which is the row count (as per your "delete row"); your pseudo-code was using the count of columns to decide whether to delete rows.