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?

5
  • 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. Commented Dec 8, 2011 at 4: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.. Commented Dec 8, 2011 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. Commented Dec 8, 2011 at 13:39
  • You need to rewrite the question. As written, you've written an endless loop. Commented Dec 8, 2011 at 16:41
  • 1
    @Pursuit et al - This is not an infinite loop. See this blog post from Loren. Commented Dec 8, 2011 at 22:10

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Nice answer. There is a simple typo: The while loop should look like this: while(c<= 10)... ;-)
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
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.