Loren on the Art of MATLAB

Turn ideas into MATLAB

Note

Loren on the Art of MATLAB has been archived and will not be updated.

for Versus while

A reader suggested I discuss the difference in use of MATLAB's for and while constructs.

Contents

The Scene

You want to run some code at least once, regardless of any conditions. You might want to run it more often, depending on some conditions.

At Least Once in a while

Here's a couple of solutions using a while construct, while ensuring the main chunk of code is run at least once, even if the stop condition is already met.

  n = 0;
  i = 1;
  while true
       doStuff();
       if (i > n)
           break;
       end
       i = i + 1;
       n = somethingElse();
  end

Here's another way that inverts the logic surrounding the condition and avoids using an explicit break statement. Instead, it has to check to see that currentState is still true.

  n = 0;
  i = 1;
  currentState = true;
  while currentState
       doStuff();
       currentState = (i <= n);
       if currentState,
          i = i + 1;
          n = somethingElse();
       end
  end

I wonder if this version is any better than the first. It is one line longer so currentState can be explicitly set. This might be more readable to some of you, and less so to others.

Taking Care Using for

To make sure the code doStuff runs at least once, we need to take care using a for-loop. The reason for this is that the loop code is guaranteed to not run at all if the loop counter variable is empty. To ensure the code runs once, we need to repeat the code outside the loop. If the code being run is like this example, encapsulated in another function, then it's not so difficult to be sure we've got things right.

If instead of a single function, we have several statements to run, then we have take care to copy all of the code and ensure that we update both sets if we ever have to make some changes.

doStuff will never be run with the following code sample.

  n = 0;
  count = 0;
  for ind = 1:n
      doStuff();
      count = count + 1;
  end

To replicate the run-at-least-once behavior, we need to replicate the code before the loop.

  n = 0;
  count = 0;
  doStuff();
  for ind = 1:n
      doStuff();
      count = count + 1;
  end

Your Style Preferences?

I have to say that having lots of code in the body that might have to be replicated is something I would avoid. So I'd see if I could reasonably stick the bulk of the loop body code in another function. After that, I still have a slight preference for one style over the others, but I'd like to hear your thoughts first.

Which programming style do you prefer here? Using for, while with an explicit condition, while with a break, or do you have an even better code pattern? Post your thoughts here.




Published with MATLAB® 7.5


  • print

댓글

댓글을 남기려면 링크 를 클릭하여 MathWorks 계정에 로그인하거나 계정을 새로 만드십시오.