You are on page 1of 19

Branching Statements and Program Design

Program design process


A typical testing process for a large program
The logical data type is a special type of data that can
have one of only two possible values:
true or false
If a logical value is used in a place where a numerical
value is expected, true values are converted to 1, and
false values are converted to 0 and then used as
numbers.
If a numerical value is used in a place where a logical
value is expected, nonzero values are converted to
true, and 0 values are converted to false and then
used as logical values.
It is also possible to explicitly convert numerical values
to logical values, and vice versa. The logical function
converts numerical data to logical data, and the real
function converts logical data to numerical data.
Relational operators are operators with two numerical or
string operands that yield a logical result.
Relational operators may be used to compare a scalar value
with an array.
For example:

 1 0 1 0
a  b  0 then a  b will yield  
 2 1   0 1 

If the arrays have different sizes, a run-time error will result.

Since strings are really array of characters, relational


operators can only compare two strings it they are equal
lengths.If they are of unequal lengths, the comparison
operation will produce an error.
These operators can produce sometimes surprising
results when two numeric values are compared.
Due to round off errors during computer
calculations, two theoretically equal numbers can
differ slightly, causing an equality or inequality test
to fail.
>>a=0;
>>b=sin(pi);
>>a==b
>>ans=0 use this instead
>> abs(a-b) < 1.0e-14
Note that there are two logical AND operators:&& and &. What is the
difference between them? The basic difference is that && supports
partial evaluations while & doesn’t. That is, && will evaluate left
expression and immediately return a false value if left expression is
false. The operator never evaluates right expression because the
result ot the operator will be false regardless of the value of the right
expression.
A second difference is that && works only between scalar values,
whereas & works with either scalar or array values, as long as sizes
are compatible.
Sometimes it is important to use shortcut expressions. For example,
suppose that we wanted to test for the situation where ratio of two variables
a and b is greater than 10. The code to perform this test is:

x= a/b > 10.0

The test could be modified to avoid division by 0 problem as

x= (b~=0) && (a/b > 10.0)


Use the & AND operator if it is necessary to ensure that both
operands are evaluated in an expression, or if the comparison is
between arrays.
Otherwise, use the && AND operator, since the partial evaluation
will make the operation faster in the cases where the first operand
is false. The & operator is preferred in most practical cases.

Using Numeric Data with Logic Operators

Real numeric data can also be use with logic operators. Since logic
operators expect logical input values, MATLAB converts nonzero
values to true and zero values to false before performing the
operation. Thus,
the result of ~5 is false (0 in the Command Window)
the result of ~0 is true (1 in the Command Window)
Logic operators may be used to compare a scalar value with an array.
For example, if

 true false   false false 


a b  false then a & b will yield 
 false true   false false 

0 0
(displayed as   in the Command Window).
0 0
Logic operators may also be used to compare two arrays, as long as
both arrays have the same size. For example, if

 true false   true true   true true 


a  b  then a | b will yield  
 false true   false false   false true 
 1 1
(displayed as
 0 1 in the Command Window).
 
If the arrays have different sizes, a run-time error will result.
Logic operators may not be used with complex or imaginary
numeric data.
For example, an expression such as “2i & 2i” will produce an error
when it is evaluated.

Hierarchy of Operations

1. All arithmetic operators are evaluated first in the order


previously described.
2. All relational operators (==, ~=, >, >=, <, <=) are evaluated,
working from left to right.
3. All ~ operators are evaluated.
4. All & and && operators are evaluated, working from left to right.
5. All |, ||, and xor operators are evaluated, working from left to
right.
As with arithmetic operations, parentheses can be used to change
the default order of evaluation
Branches are MATLAB statements that permit us to select
and execute specific sections of code (called blocks)
while skipping other sections of code. They are
variations of the if construct, the switch construct, and
the try/catch construct.
The if Construct
if control_expr_1
Statement 1
Statement 2
...
elseif control_expr_2
Statement 1
Statement 2
...
else
Statement 1
Statement 2
...
end
The switch Construct
The switch construct is another form of branching construct. It
permits a programmer to select a particular code block to execute
based on the value of a single integer, character, or logical
expression.
The general form of a switch construct is
switch (switch_expr)
case case_expr_1
Statement 1
Statement 2
...
case case_expr_2
Statement 1
Statement 2
...
otherwise
Statement 1
Statement 2
...
end
If many values of the switch_expr should cause the same code to
execute, all of those values may be included in a single block by
enclosing them in brackets, as shown in the following statements.
If the switch expression matches any of the case expressions in
the list, then the block will be executed.

switch (switch_expr)
case {case_expr_1, case_expr_2, case_expr_3}
Statement 1
Statement 2
...
otherwise
Statement 1
Statement 2
...
end
The switch_expr and each case_expr may be either numerical or
string values.

Let’s look at a simple example of a switch construct.

switch (value)
case {1,3,5,7,9}
disp('The value is odd.');
case {2,4,6,8,10}
disp('The value is even.');
otherwise
disp('The value is out of range.');
end
The try/catch Construct
The try/catch construct is a special form branching construct
designed to trap errors. Ordinarily, when a MATLAB program
encounters an error while running, the program aborts. The try/catch
construct modifies this default behavior. If an error occurs in a
statement in the try block of this construct, then instead of aborting,
the code in the catch block is executed and the program keeps
running. This allows a programmer to handle errors within the
program without causing the program to stop.
The general form of a try/catch construct is as follows:
try
Statement 1
Statement 2
...
catch
Statement 1
Statement 2
...
end
% Initialize array
a = [ 1 -3 2 5];
try
% Try to display an element
index = input('Enter subscript of element to display: ');
disp( ['a(' int2str(index) ') = ' num2str(a(index))] );
catch
% If we get here an error occurred
disp( ['Illegal subscript: ' int2str(index)] );
end

When this program is executed, the results are as follows:


» try_catch
Enter subscript of element to display: 3
a(3) = 2
» try_catch
Enter subscript of element to display: 8
Illegal subscript: 8

You might also like