6/28/2018
1
C/C++ Programming for Engineers:Matlab Branches and Loops
John T. Bell
Department of Computer ScienceUniversity of Illinois, Chicago
2
Review
What is the difference between a script and a function in Matlab?
A. The first line of a function file must start with the word “function”, followed by the name of the function and a list of input and output arguments, following a specified format.
B. Script variables share scope with the main Matlab workspace, while function variables have their own local scope.
C. Functions are scripts that have been pre-compiled into binary format, so that they run faster and are not available for inspection by users.
D. Both A and B. E. Both A and C.
6/28/2018
2
3
A Common Iterative Approach
Max # of iterationsreached?
Initialize ProblemSet initial “solution”
Improve solution
Current solutiongood enough?
No
No
Report best results found
Yes
Yes
% Calculate initial solution% Estimate initial error
for counter = 1:limit
if( abs( error ) < tol )break;
end
% Improve solution% Estimate error
end
% Report best solution found,% # of iterations, and estimated error.
or here
4
Branches and Loops
• Branches ( decision making ) and loops are two of the most important constructs in computer programming.
• Branches allow code to optionally execute different code ( or none at all ) depending on the values of variables and other criteria.
• Loops make code repeat execution, possibly millions of times per second.
6/28/2018
3
5
Matlab if-else Construct
• Syntax:
if( condition )
% code to execute if true
else % else and false code are optional
% code to execute if false
end % This line is required, to mark end of “if”
• If the “condition” is a matrix, it is considered to be “true” if any part of it is true ( non-zero ).
6
Matlab Relational Operators
• No spaces allowed in <=, >=, ==, or ~=
• WARNING: Do not confuse == with = !
• If a and b are matrices, then result is a matrix.
Relational operators Result is true if and only if:
a < b a is less than b
a > b a is greater than b
a <= b a is less than or equal to b
a >= b a is greater than or equal tob
a == b a is equal to b
a ~= b a is not equal to b
6/28/2018
4
7
Combined Ifs
• Either the true or false clauses of an if may contain any other code, including other ifs.
• When the true clause of an if contains another if, it is termed “nested”.
• When the false clause of an if contains another if, it is termed “sequential”. It is not uncommon to see long strings of sequential ifs.
8
A Nested If Example
if( X <= 0.0 )
if( X < 0.0 )
fprintf( ‘Negative’ );
else
fprintf( ‘Zero’ );
end
else
fprintf( ‘Positive’ );
end
6/28/2018
5
9
Sequential Ifs in Matlab
• Matlab has an “elseif” keyword for use in sequential ifs:if( condition )
% code to execute if true
elseif( condition2 ) % Any number of these, optional
% code to execute if sequential condition2 is true
else % else and false code are optional
% code to execute if false
end% This is required
10
A Sequential If Example
if( X < 0.0 )
fprintf( ‘Negative’ );
elseif( X > 0.0 )
fprintf( ‘Positive’ );
else
fprintf( ‘Zero’ );
end
6/28/2018
6
11
A Longer Sequential If Example
if( score >= 90.0)
fprintf( ‘A’ );
elseif( score >= 80.0)
fprintf( ‘B’ );
elseif( score >= 70.0)
fprintf( ‘C’ );
elseif( score >= 60.0)
fprintf( ‘D’ );
else
fprintf( ‘F’ );
end
Note that the order of the tests is important in this example.
12
In a series of sequential ifs,How many clauses will be executed?
A. Every one that is true.
B. The first one that is true.
C. One of the true ones, but which one may be machine and compiler dependent.
D. An error will occur if more than one clause is true.
E. The first one if it is true, otherwise none at all.
6/28/2018
7
13
Matlab Logical Operators
Logical operator Equivalent function Description
a & b and(a,b) Returns true if a and b are true, meaning both are true.
a | b or(a,b) Returns true if a or b is true, meaning either is true (or both).
~a not(a) Negates or complements the value of a, returning true if a is false, and vice versa.
xor(a,b)
Returns true if a is true or b is true but not both, i.e., if exactly one of a or b is true. Known as exclusive or or xor (the x comes from eXclusive).
14
& vs. && and | vs. ||
• Matlab has two forms of the logical AND and OR operators, using one or two symbols.
• When dealing with matrices, the single-character versions act element-by-element, producing a matrix of results.
• The double-character versions are only usable with scalars, and perform short-circuit evaluation, stopping as soon as the result is known.– Example: if( x ~= 0 && 1.0 / x > tol ) won’t divide by 0
6/28/2018
8
15
Precedence for Logical Operators
Convention Description Explanation
( )Items within parentheses are evaluated first.
~ not (negation) is evaluated next.For example, ~ a & b evaluates as (~a) & b.
& and is evaluated after not.
Thus a & b | c evaluates as (a & b) | c. The expression will always be true if both and and b are true, for example.
| Last to be evaluated is or.
left-to-rightIf more than one operator of equal precedence could be evaluated, evaluation occurs left to right.
Thus, a | b | c evaluates as (a | b) | c.
16
How do you check if X is between 0 and 10 ?
A. if( 0.0 < X < 10.0 )
B. if( 0.0 <= X <= 10.0 )
C. if( 0.0 < X && X < 10.0 )
D. if( 0.0 <= X && X <= 10.0 )
E. if( 0.0 < X || X < 10.0 )
6/28/2018
9
17
Matlab Relational & Logical Functions
Function Description
any(x)Returns true if x is nonzero; otherwise, returns false.
isnan(x)Returns true if x is NaN (Not-a-Number); otherwise, returns false.
isfinite(x)
Returns true if x is finite; otherwise, returns false. For example, isfinite(Inf) is false, and isfinite(10) is true.
isinf(x)Returns true if x is +Inf or -Inf; otherwise, returns false.
19
Matlab While Loop Syntax
while( condition )
% code in body of loop
end % required
• Matlab does not have do-while, but does have break & continue to be explained later.
condition?
body
Followingcode
False
True
6/28/2018
10
20
Input Checking With a While Loop
age = -1; % Initialized to guarantee loop entry
while( age < 0 || age > 120 )
age = input( ‘Please enter your age: ‘);
if( age < 0 || age > 120 )
fprintf( ‘%d is invalid. Try again.\n’, age );
fprintf( ‘Valid ages are from 0 to 120.\n’);
end
end % Continue while input is bad
21
Matlab “for” loops
• Syntax:
for variable = List_of_Values
% Code to execute for each value on the list.
end % required
• The loop will execute as many times as there are values on the list, with “variable” taking on a separate value from the list each iteration.
• Sample lists: 1:10, 0:0.1*pi:pi, [ 3, 5, 8, 11 ], X
6/28/2018
11
22
Break and Continue
• “break” causes a loop to finish immediately, continuing execution with the code following the loop body.
• “continue” causes the current iteration of a loop to finish, starting the next iteration.– While loops will jump to the evaluation of the
loop condition.
– For loops will set the loop variable to the next item on the list, provided there are items left.
23
For Loop Flowchart Illustrating break and continue
for var in list
% code 1
if( test_C )
continue;
% code 2
if( test_B )
break;
% code 3
end
items remain?
code 1
Following code
False
True
set var to next item
init var to 1st list item
code 2
code 3
test_C
test_B
True
6/28/2018
12
24
Input Checking With an Infinite Loop
while( true ) % Infinite loop, until good input is given
age = input( ‘Please enter your age: ‘);
if( age >= 0 && age <= 120 )
break; % Exit loop only when good input
end
fprintf( ‘%d is invalid. Try again.\n’, age );
fprintf( ‘Valid ages are from 0 to 120.\n’);
end % Continue while input is bad
25
Matlab Loops and Arrays
• It is generally NOT a good idea to use loops to access Matlab array elements. Instead use the power of Matlab to operate on entire arrays ( or subsets thereof ) in one operation.
• If you must use a loop to build an array element-by-element, pre-size it first to speed up operations, instead of growing the array by one element each loop iteration.
6/28/2018
13
26
Consider a case where a variable is checked against a list of choices:
direction = input( ‘Which way ?, NSEW ?’, …‘s’ );
if( direction == ‘W’ ) % Go WestX = X - 1;
elseif ( direction == ‘E’ ) % EastX = X + 1;
else if ( direction == ‘N’ ) % NorthY = Y + 1;
else if( direction == ‘S’ ) % SouthY = Y - 1;
elsefprintf( ‘Illegal Move.\n’ );
end
switch( direction ) case ‘W’ % Go West
X = X - 1;case ‘E’ % East
X = X + 1;case ‘N’ % North
Y = Y + 1;case ‘S’ % South
Y = Y - 1;otherwise
fprintf( ‘Illegal Move. \n’ );end
27
Matlab “switch” construct
• Syntax:switch( expression )
case caseExpr1
% code to execute if expression == caseExpr1
% Add additional cases as needed
otherwise
% code to execute if no case expressions match
end % required
• Case expressions must be scalars. ( or strings or cells )
• No fall-through from one case to the next.
6/28/2018
14
29
Review
Which of the following C++ logic constructs is NOT available in Matlab?
A. if-else construct
B. for loops
C. while loops
D. do-while loops
E. switch construct