Summary: This is a tutorial on using while loops in MATLAB.
Note: You are viewing an old version of this document. The latest version is available here.
The while loop is similar to the for loop in that it allows the repeated execution of MATLAB statements. Unlike the for loop, the number of times that the MATLAB statements in the body of the loop are executed can depend on variable values that are computed in the loop. The syntax of the while loop has the following form:
while expression
% MATLAB command 1
% MATLAB command 2
% More commands to execute repeatedly until expression is not true
end
where expression is a logical expression that is either true or false. (Information about logical expressions is available in Programming in MATLAB-Logical Expressions.)
For example, consider the following while loop:
n = 1
while n < 3
n = n+1
end
This code creates the following output:
n =
1
n =
2
n =
3
Note that in all of this example, the MATLAB commands inside the while loop are indented relative to the while and end statements. This is not required by MATLAB but is common practice and makes the code much more readable.