C/C++ Programming for Engineers: Matlab Branches and Loops John T. Bell Department of Computer Science University of Illinois, Chicago 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. 2 1
A Common Iterative Approach Initialize Problem Set initial solution % Calculate initial solution % Estimate initial error for counter = 1:limit Current solution good enough? No Max # of iterations reached? No Improve solution Yes Yes Report best results found if( abs( error ) < tol ) break; % Improve solution % Estimate error or here % Report best solution found, % # of iterations, and estimated error. 3 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 ) deping on the values of variables and other criteria. Loops make code repeat execution, possibly millions of times per second. 4 2
Matlab if-else Construct Syntax: if( condition ) % code to execute if true else % else and false code are optional % code to execute if false % This line is required, to mark of if If the condition is a matrix, it is considered to be true if any part of it is true ( non-zero ). 5 Matlab Relational Operators Relational operators a < b a > b a <= b a >= b a == b a ~= b Result is true if and only if: a is less than b a is greater than b a is less than or equal to b a is greater than or equal to b a is equal to b a is not equal to b No spaces allowed in <=, >=, ==, or ~= WARNING: Do not confuse == with =! If a and b are matrices, then result is a matrix. 6 3
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. 7 A Nested If Example if( X <= 0.0 ) if( X < 0.0 ) fprintf( Negative ); else fprintf( Zero ); else fprintf( Positive ); 8 4
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 % This is required 9 A Sequential If Example if( X < 0.0 ) fprintf( Negative ); elseif( X > 0.0 ) fprintf( Positive ); else fprintf( Zero ); 10 5
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 ); Note that the order of the tests is important in this example. 11 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 depent. D. An error will occur if more than one clause is true. E. The first one if it is true, otherwise none at all. 12 6
Matlab Logical Operators Logical operator Equivalent function Description a & b a b and(a,b) or(a,b) ~a not(a) xor(a,b) Returns true if a and b are true, meaning both are true. Returns true if a or b is true, meaning either is true (or both). Negates or complements the value of a, returning true if a is false, and vice versa. 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). 13 & 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 14 7
Precedence for Logical Operators Convention Description Explanation ( ) Items within parentheses are evaluated first. ~ not (negation) is evaluated next. & and is evaluated after not. Last to be evaluated is or. left-to-right If more than one operator of equal precedence could be evaluated, evaluation occurs left to right. For example, ~ a & b evaluates as (~a) & b. Thus a & b c evaluates as (a & b) c. The expression will always be true if both and and b are true, for example. Thus, a b c evaluates as (a b) c. 15 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 ) 16 8
Matlab Relational & Logical Functions Function any(x) isnan(x) isfinite(x) isinf(x) Description Returns true if x is nonzero; otherwise, returns false. Returns true if x is NaN (Not-a- Number); otherwise, returns false. Returns true if x is finite; otherwise, returns false. For example, isfinite(inf) is false, and isfinite(10) is true. Returns true if x is +Inf or -Inf; otherwise, returns false. 17 Matlab While Loop Syntax while( condition ) % code in body of loop % required Matlab does not have do-while, but does have break & continue to be explained later. condition? True body Following code False 19 9
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 ); % Continue while input is bad 20 Matlab for loops Syntax: for variable = List_of_Values % Code to execute for each value on the list. % 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 21 10
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. 22 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 set var to next item init var to 1 st list item True items remain? code 1 test_c code 2 test_b code 3 Following code True False 23 11
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 fprintf( %d is invalid. Try again.\n, age ); fprintf( Valid ages are from 0 to 120.\n ); % Continue while input is bad 24 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. 25 12
Consider a case where a variable is checked against a list of choices: direction = input( Which way?, NSEW?, s ); if( direction == W ) % Go West X = X - 1; elseif ( direction == E ) % East X = X + 1; else if ( direction == N ) % North Y = Y + 1; else if( direction == S ) % South Y = Y - 1; else fprintf( Illegal Move.\n ); 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 ); 26 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 % required Case expressions must be scalars. ( or strings or cells ) No fall-through from one case to the next. 27 13
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 29 14