MATLAB: Global variable in for loop

for loopMATLAB

Hi,
I have a for loop, which has last iterative defined as the size of some matrix K, i.e.
[a,b]=size(K)
for i=1:a
CODE
end
Trouble is, the "CODE" in the for loop redefines how large K is – in particular, it decreases a. This means that the for loop experiences an "Index exceeds matrix dimensions." error. How does one go about fixing this? I thought that in the for loop I could have:
a=a-1;
everytime the "CODE" decreases the size of K, but it don't work none!
Thanks,
Linford

Best Answer

If you are deleting the entry you are examining under some circumstances, then the easiest change is often to run the loop backwards .