1. LOOPS AND EXECUTION
CONTROL
DR. DIVYA PRIYA B.
ASSISTANT PROFESSOR, IRS
DEPARTMENT OF CIVIL ENGINEERING
ANNA UNIVERSITY, CHENNAI.
2. A computer program is a sequence of computer commands. In a simple program the
commands are executed one after the other in the order they are typed.
So far all the programs that have been presented so far in script files are simple
programs.
Many situations, however, require more sophisticated programs in which commands
are not necessarily executed in the order they are typed, or different commands
(or groups of commands) are executed when the program runs with different input
variables.
For example, a computer program that calculates the cost of mailing a package
uses different mathematical expressions to calculate the cost depending on the
weight and size of the package, the content (books are less expensive to mail), and
the type of service (airmail, ground, etc.). In other situations there might be a need
to repeat a sequence of commands several times within a program. For example,
programs that solve equations numerically repeat a sequence of calculations until
the error in the answer is smaller than some measure
3. MATLAB provides several tools that can be used to control the flow of a
program. Conditional statements and the switch structure make it possible to
skip commands or to execute specific groups of commands in different
situations.
For loops and while loops make it possible to repeat a sequence of commands
several times. It is obvious that changing the flow of a program requires some
kind of decision-making process within the program.
The computer must decide whether to execute the next command or to skip one
or more commands and continue at a different line in the program.
The program makes these decisions by comparing values of variables. This is
done by using relational and logical operators.
4. RELATIONAL AND LOGICAL OPERATORS
A relational operator compares two numbers by determining whether a comparison statement
(e.g., 5 < 8) is true or false.
If the statement is true, it is assigned a value of 1. If the statement is false, it is assigned a value
of 0. A logical operator examines true/false statements and produces a result that is true (1) or
false (0) according to the specific operator.
For example, the logical AND operator gives 1 only if both statements are true. Relational and
logical operators can be used in mathematical expressions and, are frequently used in
combination with other commands, to make decisions that control the flow of a computer program
5. Note that the “equal to” relational operator consists of two = signs (with no space
between them), since one = sign is the assignment operator. In other relational
operators that consist of two characters there also is no space between the characters
(<=, >=, ~=).
• Relational operators are used as arithmetic operators within a mathematical expression.
The result can be used in other mathematical operations, in addressing arrays, and
together with other MATLAB commands (e.g., if) to control the flow of a program.
• When two numbers are compared, the result is 1 (logical true) if the comparison,
according to the relational operator, is true, and 0 (logical false) if the comparison is
false.
• If two scalars are compared, the result is a scalar 1 or 0. If two arrays are compared
(only arrays of the same size can be compared), the comparison is done element-by-
element, and the result is a logical array of the same size with 1s and 0s according to
the outcome of the comparison at each address.
6. If a scalar is compared with an array, the scalar is compared with every
element of the array, and the result is a logical array with 1s and 0s
according to the outcome of the comparison of each element.
14. If two or more operations have the same precedence, the expression is executed in
order from left to right. It should be pointed out here that the order shown above is
the one used since MATLAB 6. Previous versions of MATLAB used a slightly different
order (& did not have precedence over |), so the user must be careful.
Compatibility problems between different versions of MATLAB can be avoided by
using parentheses even when they are not required.
16. Built-in logical functions: MATLAB has built-in functions that are equivalent to the logical
operators. These functions are:
and (A,B) equivalent to A&B
or (A,B) equivalent to A|B
not(A) equivalent to ~A
22. CONDITIONAL STATEMENTS
A conditional statement is a command that allows MATLAB to make a decision of
whether to execute a group of commands that follow the conditional statement, or to
skip these commands. In a conditional statement a conditional expression is stated. If
the expression is true, a group of commands that follow the statement are executed.
If the expression is false, the computer skips the group. The basic form of a
conditional statement is:
23. The if-end Structure
The if-end conditional statement is shown schematically in Figure 6-1. The figure shows
how the commands are typed in the program, and a flowchart that symbolically shows
the flow, or the sequence, in which the commands are executed. As the program
executes, it reaches the if statement.
If the conditional expression in the if statement is true (1), the program continues to
execute the commands that follow the if statement all the way down to the end
statement. If the conditional expression is false (0), the program skips the group of
commands between the if and the end, and continues with the commands that follow
the end
The words if and end appear on the screen in blue, and the commands between
the if statement and the end statement are automatically indented (they don’t
have to be), which makes the program easier to read.
25. A worker is paid according to his hourly wage up to 40 hours, and 50% more for
overtime. Write a program in a script file that calculates the pay to a worker. The
program asks the user to enter the number of hours and the hourly wage. The program
then displays the pay
28. The if-else-end Structure
commands are executed. The first line is an if statement with a conditional
expression. If the conditional expression is true, the program executes group 1 of
commands between the if and the else statements and then skips to the end. If the
conditional expression is false, the program skips to the else and then executes
group 2 of commands between the else and the end
29. The if-elseif-else-end Structure
The if-elseif-else-end structure is shown in Figure 6-3. The figure shows how the
commands are typed in the program, and gives a flowchart that illustrates the flow, or
the sequence, in which the commands are executed.
This structure includes two conditional statements (if and elseif) that make it possible to
select one out of three groups of commands for execution. The first line is an if
statement with a conditional expression. If the conditional expression is true, the
program executes group 1 of commands between the if and the elseif statements and
then skips to the end. If the conditional expression in the if statement is false, the
program skips to the elseif statement. If the conditional expression in the elseif
statement is true, the program executes group 2 of commands between the elseif and
the else and then skips to the end. If the conditional expression in the elseif statement is
false, the program skips to the else and executes group 3 of commands between the
else and the end. It should be pointed out here that several elseif statements and
associated groups of commands can be added. In this way more conditions can be
included. Also, the else statement is optional. This means that in the case of several
elseif statements and no else statement, if any of the conditional statements is true the
associated commands are executed; otherwise nothing is executed. The following
example uses the if-elseif-else-end structure in a program
36. How does the switch-case statement work?
The value of the switch expression in the switch command is compared with the
values that are next to each of the case statements. If a match is found, the group
of commands that follow the case statement with the match are executed. (Only
one group of commands—the one between the case that matches and either the
case, otherwise, or end statement that is next—is executed).
• If there is more than one match, only the first matching case is executed.
• If no match is found and the otherwise statement (which is optional) is present, the
group of commands between otherwise and end is executed.
• If no match is found and the otherwise statement is not present, none of the
command groups is executed.
• A case statement can have more than one value. This is done by typing the values
in the form: {value1, value2, value3, ...}. (This form, which is not covered in this
book, is called a cell array.) The case is executed if at least one of the values
matches the value of switch expression.
A Note: In MATLAB only the first matching case is executed. After the group of
commands associated with the first matching case are executed, the program skips
to the end statement. This is different from the C language, where break
statements are required
37. LOOPS
A loop is another method to alter the flow of a computer program.
In a loop, the execution of a command, or a group of commands, is
repeated several times consecutively. Each round of execution is
called a pass. In each pass at least one variable, but usually more
than one, or even all the variables that are defined within the loop,
are assigned new values.
MATLAB has two kinds of loops. In for-end loops, the number of
passes is specified when the loop starts.
In while-end loops the number of passes is not known ahead of
time, and the looping process continues until a specified condition is
satisfied. Both kinds of loops can be terminated at any time with
the break command
38. For-end Loops
In for-end loops the execution of a command, or a group of commands, is repeated
a predetermined number of times.
The form of a loop is shown in Figure •
The loop index variable can have any variable name (usually i, j, k, m, and n are
used, however, i and j should not be used if MATLAB is used with complex
numbers).
39. In the first pass k = f and the computer executes the commands
between the for and end commands. Then, the program goes
back to the for command for the second pass. k obtains a new
value equal to k = f + s, and the commands between the for
and end commands are executed with the new value of k. The
process repeats itself until the last pass, where k = t. Then the
program does not go back to the for, but continues with the
commands that follow the end command. For example, if k =
1:2:9, there are five loops, and the corresponding values of k
are 1, 3, 5, 7, and 9.
• The increment s can be negative (i.e.; k = 25:–5:10 produces
four passes with k = 25, 20, 15, 10). • If the increment value s
is omitted, the value is 1 (default) (i.e.; k = 3:7 produces five
passes with k = 3, 4, 5, 6, 7).
40. • If f = t, the loop is executed once.
• If f > t and s > 0, or if f < t and s < 0, the loop is not executed.
• If the values of k, s, and t are such that k cannot be equal to t,
then if s is positive, the last pass is the one where k has the largest
value that is smaller than t (i.e., k = 8:10:50 produces five passes
with k = 8, 18, 28, 38, 48). If s is negative, the last pass is the one
where k has the smallest value that is larger than t.
• In the for command k can also be assigned a specific value
(typed as a vector). Example: for k = [7 9 –1 3 3 5].
• The value of k should not be redefined within the loop.
• Each for command in a program must have an end command.
• The value of the loop index variable (k) is not displayed
automatically. It is possible to display the value in each pass (whic
is sometimes useful for debugging) by typing k as one of the
commands in the loop.
When the loop ends, the loop index variable (k) has the value tha
was last assigned to it.
46. while-end Loops
While-end loops are used in situations when looping is needed but the number of passes
is not known in advance. In while-end loops the number of passes is not specified when
the looping process starts. Instead, the looping process continues until a stated condition is
satisfied. The structure of a while-end loop is shown in Figure
The first line is a while statement that includes a conditional expression. When the program
reaches this line the conditional expression is checked. If it is false (0), MATLAB skips to the
end statement and continues with the program. If the conditional expression is true (1),
MATLAB executes the group of commands that follow between the while and end commands.
Then MATLAB jumps back to the while command and checks the conditional expression. This
looping process continues until the conditional expression is false.
47. For a while-end loop to execute properly:
• The conditional expression in the while command must include at least one variable.
• The variables in the conditional expression must have assigned values when
MATLAB executes the while command for the first time.
• At least one of the variables in the conditional expression must be assigned a new
value in the commands that are between the while and the end.
Otherwise, once the looping starts it will never stop since the conditional expression
will remain true
48. An example of a simple while-end loop is shown in the following program.
In this program a variable x with an initial value of 1 is doubled in each
pass as long as its value is equal to or smaller than 15.
53. NESTED LOOPS AND NESTED CONDITIONAL STATEMENTS
Loops and conditional statements can be nested within other loops or conditional
statements. This means that a loop and/or a conditional statement can start (and end)
within another loop or conditional statement. There is no limit to the number of loops and
conditional statements that can be nested. It must be remembered, however, that each if,
case, for, and while statement must have a corresponding end statement. Figure shows the
structure of a nested for-end loop within another for-end loop. In the loops shown in this
figure, if, for example, n = 3 and m = 4, then first k = 1 and the nested loop executes
four times with h = 1, 2, 3, 4. Next k = 2 and the nested loop executes again four times
with h = 1, 2, 3, 4. Finally k = 3 and the nested loop executes again four times. Every time
a nested loop is typed, MATLAB automatically indents the new loop relative to the outside
loop. Nested loops and conditional statements are demonstrated in the following sample
problem.
55. THE break AND continue COMMANDS
The break command:
• When inside a loop (for or while), the break command terminates the execution
of the loop (the whole loop, not just the last pass). When the break command
appears in a loop, MATLAB jumps to the end command of the loop and continues
with the next command (it does not go back to the for command of that loop).
• If the break command is inside a nested loop, only the nested loop is
terminated.
• When a break command appears outside a loop in a script or function file, it
terminates the execution of the file.
• The break command is usually used within a conditional statement. In loops it
provides a method to terminate the looping process if some condition is met —for
example, if the number of loops exceeds a predetermined value, or an error in
some numerical procedure is smaller than a predetermined value. When typed
outside a loop, the break command provides a means to terminate the execution
of a file, such as when data transferred into a function file is not consistent with
what is expected
56. The continue command:
• The continue command can be used inside a loop (for or while) to stop the present
pass and start the next pass in the looping process.
• The continue command is usually a part of a conditional statement.
When MATLAB reaches the continue command, it does not execute the remaining
commands in the loop, but skips to the end command of the loop and then starts a new
pass.