Matlab – Loop types
There may be a situation when you need to execute a block of code several times. In general,
statements are executed sequentially. The first statement in a function is executed first, followed by the
second, and so on.
Programming languages provide various control structures that allow
for more complicated execution paths.
A loop statement allows us to execute a statement or group of
statements multiple times. The drawing shows the general form of a
loop statement for most programming languages.
Matlab provides various types of loops to handle looping requirements
including: while loops, for loops, and nested loops. If you are trying to
declare or write your own loops, you need to make sure that the loops
are written as scripts and not directly in the Command Window.
To start a new script, locate the button in the upper left corner of the window labeled New Script.
While Loop
The while loop repeatedly executes statements while a specified condition is true.
The syntax of a while loop in MATLAB is as following:
while <expression>
<statements>
end
The while loop repeatedly executes a program statement(s) as long as the expression remains true.
An expression is true when the result is nonempty and contains all nonzero elements (logical or real
numeric). Otherwise, the expression is false.
Example
a = 10;
% while loop execution
while( a < 20 )
fprintf('value of a: %d\n', a);
a = a + 1;
end
When the code above is executed, the result will be: