2

I have a loop like this:

b = 1;
for c = 1 : 10;
  if b == 1
      c = 1 + 3
  end
end

What do I need to do to make to change c? Because as I read through the help, MATLAB resets the loop counter c after it reaches end.

Is there any way to change the value of the loop counter from within a for loop?

Egon
  • 4,757
  • 1
  • 23
  • 38
Adrian Hartanto
  • 43
  • 1
  • 2
  • 6
  • Do you mean `c = c + 3`? As written, it looks like you intend for the loop to never end, since `c` would always be set to `4`. – Pursuit Dec 08 '11 at 04:26
  • yes sir, what i mean is, that the loop in the for loops, will change its values to 4, and then growng, but in that code i think thats only make a 4, but still 10 times looping.. – Adrian Hartanto Dec 08 '11 at 11:34
  • 1
    I would always avoid modifying loop indices within a loop - this can lead to some hard to find bugs. Either of the answers below are better ways of doing what you want. – Chris Dec 08 '11 at 13:39
  • You need to rewrite the question. As written, you've written an endless loop. – Marc Dec 08 '11 at 16:41
  • 1
    @Pursuit et al - This is not an infinite loop. See [this blog post from Loren](http://blogs.mathworks.com/loren/2006/07/19/how-for-works/#5). – Dang Khoa Dec 08 '11 at 22:10

2 Answers2

10

you could use a while loop instead of a for loop.

something like (I'm guessing you want to add 3 to c otherwise c = 4 could replace that line below)

b = 1;
c = 1;
while(c < 10)
    if b == 1
        c = c + 3
    end
end
smitec
  • 3,049
  • 1
  • 16
  • 12
2

Not really following what you're trying to do but are you looking to increase the value of c by 3 as opposed to 1 on each iteration of the loop?

You can do that with:

for i = 1:3:10
    // do something
end

this is the equivalent of the more common for loop syntax:

for (c = 1; c <= 10; c+=3)
{
    // do something
}
Peadar Doyle
  • 1,064
  • 2
  • 10
  • 26