266

Using loops in Matlab


Article posted on Sunday, 11th, August, 2013 at 6:11 pm


So if you’ve read my previous posts on Matlab, you’ve learned a few basics, and have an idea about how 1D arrays are made. Now to discuss the joy of looping and how it can save you oodles of time…

So loops in Matlab are essentially lines of code which get repeated. Depending on the method you choose, the code that you use to create a loop will either specify the conditions required for Matlab to continue looping, or explicitly state how many times the code should loop.

To illustrate the way loops work, we’re going to get Matlab to write some lines. Now I don’t know why you’d want to ordinarily do this, unless you want to punish Matlab in some way, but it’s as good an example as any! Let’s start by trying a for loop.

For Loops

number_of_loops = 20;

for counter = 1:number_of_loops

  disp(['I can't believe that I have to write this ', num2str(number_of_loops), ' times!'])

end

Would have been useful writing lines at school eh?

A quick note about the disp function here: as you’re probably aware, disp just outputs text neatly to the command line. What we’re doing is slightly more complex, as we’re converting our number_of_loops variable to a string using num2str (disp doesn’t play with numbers), and joining the strings together, using the square brackets. This gives us one line of text that includes a numeric variable.

While Loops

While loops work much the same way as for loops, but instead of specifying the number of iterations Matlab will work through beforehand, the while loop will iterate until a specific criteria is met. This means you can write while loops in a very similar manner to for loops, but also allows for flexibility in iterating until a variable has changed sufficiently.

Here’s an example of a while loop working like a for loop:

counter = 1;
number_of_loops = 20;

while counter < number_of_loops

  disp(['I can't believe that I have to write this ', num2str(number_of_loops), ' times!'])
  counter = counter + 1;

end

The while loop has a counter, which increases by one each time, and there is a maximum number of iterations, specified by number_of_loops. Note that the responsibility for altering the variable specified in the while condition is yours! Make sure it changes each time it loops, otherwise you’ll be looping forever!

The while loop can iterate based on unpredictable changes to a variable as well. A simplifed example using a random number generator tries to illustrate this point:

number = 0;

while number < 100

  disp('I have no idea how long I need to do this for!')
  number = number + randi(10);

end

So here, each iteration generates a random number between 1 and 10 and adds it to our number variable. The while loop will continue to run until the number variable becomes equal to or greater than 100. This isn’t a particularly useful example, but you should get the idea of how it is different to a for loop.

break – your “Get out of Loop Free Card”

The break keyword is a handy tool for exiting out of a loop, if a separate condition is met. These conditions are typically specified using if statements, although there are other evaluative methods for triggering breaks. The simple example below breaks out of a loop if a randomly generated number is equal to 7.

number_of_loops = 20;

for counter = 1:number_of_loops

  disp(['I can't believe that I have to write this ', num2str(number_of_loops), ' times!'])

  if randi(10) == 7
      disp('Cool! I don't have to do this any more!')
    break;
  end  

end

I’m sure there are more sensible examples, but I’m sure as hell not going to teach you them

Enjoy!





Join in the Conversation


comments powered by Disqus