1

Why does the following code

for a=1:5:100
    a = a+ 1;
end

iterate 20 times?

a goes up by 5 every iteration, but also goes up by 1 in the actual loop. 99/6 = 16.5 or 17 iterations, so why does it do 20?

Thanks for any help understanding how the for loop function works.

chappjc
  • 30,359
  • 6
  • 75
  • 132

3 Answers3

4

In Matlab, whatever you do to the loop index variable (a) inside a for loop is thrown away, and a gets reset at the beginning of the next pass. So the a = a + 1 inside the loop has no effect. See Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?.

Community
  • 1
  • 1
Andrew Janke
  • 23,508
  • 5
  • 56
  • 85
1

Unlike languages like C or C++, changing the loop index in MATLAB is not persistent across loop iterations.

In other words, if you increment a, it will remain incremented for the rest of that loop. However, upon reaching the top of the loop, MATLAB does not add 5 to a. Instead, it selects the next value of a from the list of values you provided. This effectively "overwrites" the change that you made to the loop index inside the loop.

Glenn
  • 1,059
  • 6
  • 14
0

The way to view a for loop in MATLAB like this one,

for a=1:5:100

Is to provide an array directly,

ai = [1:5:100];
for a = ai

The loop will iterate over the values in ai. Period. It doesn't matter what you do to a in the loop. At the beginning of each iteration, the value of a gets set according to the array given to the for statement.

chappjc
  • 30,359
  • 6
  • 75
  • 132