NathanielJPerkins
NathanielJPerkins

Reputation: 273

Number of iterations in a loop

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.

Upvotes: 1

Views: 216

Answers (3)

chappjc
chappjc

Reputation: 30579

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.

Upvotes: 0

Glenn
Glenn

Reputation: 1079

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.

Upvotes: 1

Andrew Janke
Andrew Janke

Reputation: 23848

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?.

Upvotes: 4

Related Questions