Find a Guide

While Loops in MATLAB

Introduction

The second type of loop that we will learn about in MATLAB is called a while loop. A while loop will continue to run until its initial condition is met. This allows us to run code if we do not know the number of times a piece of code needs run. Let's see some examples!

matlab

num = 4;
while num > 2
    disp(num);
    num = num - 1;
end

% output:
% 4
% 3

What is happening in the code block above is num starts out with the value of 4. The while loop then checks to see if num is greater than 2. If this is true, then a 1 will be returned and the code within the while loop will execute. This will continue until a 0 is returned for the while loop condition.

Note: make sure that the while condition returns 0 at some point, otherwise it will go on forever... or until your computer's memory is full!

Other Conditions

Another way to treat the condition for a while loop is by using a logical placeholder, for example, true or false. Let's take a look.

matlab

var = true;
count = 0;
while var
    count = count + 1;
    if count > 2
        var = false;
    end
end

In the example above, we defined the variables 'var' and 'count', and set them equal to true and 0, respectively. Then, when the while loop looks at 'var', it sees true, which is predefined as 1 in MATLAB, so then the code within the while loop executes.

Inside the while loop, the variable 'count' increments by 1 and then we check to see if 'count' is greater than 2. If it is, then we set 'var' equal to false, which then stops the while loop from continuing to execute the code. This is also a handy method to keep track of how many while loops passed.

Find a Guide