50 | Control Flow
Total Page:16
File Type:pdf, Size:1020Kb
50 j Control flow All Matlab commands considered thus far have been carried out one after the other, or, if documented in an .m file, line-by-line. This is a hallmark of imperative programming. Nevertheless, it is sometimes required to make certain commands dependent on pre-conditions, or to repeat certain commands many times for which writing them into the code many times would be tedious and error-prone. To take care of these requirements, imperative programming provides the concept of control flow. Control flow can be broken down into the interaction of essentially three components: (1) logical expressions, (2) conditional statements, and (3) loops. Logical expressions test whether certain pre-conditions hold, conditional statements then organize the evaluation of commands based on the conditional statements, and loops take care of carrying out certain commands many times. In Matlab, the most important conditional statements are if-statements, and to a lesser degree switch-statements, while the most important loops are for-loops, and two a lesser degree while-loops. We will discuss each of these concepts in turn. 50.1 Logical expressions In programming, binary logic, i.e., statements that can be either true or false (but not both or something in between), is represented by the integers 1 and 0, respectively. For example, if two scalar numerical variables x,y have been assigned a value each, one can perform a number of logical tests on them by means of the following logical expressions: x == y Is x equal to y? x ∼= y Is x not equal to y? x < y Is x smaller than y? x > y Is x larger than y? x <= y Is x smaller than or equal to y? x >= y Is x larger or or equal to y? Logical expressions can be combined by and and or operations, for which the symbols & and | are used. For example, to test whether the value of a scalar variable x is smaller than another scalar variable y and also smaller than yet another scalar variable z, we have: (x < y) & (x < z) Is x smaller than y and is x smaller than z? (x < y) | (x < z) Is x smaller than y or x smaller than z? For example, if x = 2, y = 3, and z = 4, the and expression above evaluates to true, and so does the or expression. If, however, x = 2, y = 3, and z = 1, the and expression above evaluates to false, while the or expression still evaluates to true, because x is smaller than y, and the or is non-exclusive. The brackets in the expression above are not necessary, but they help to structure the expression. In addition to the and and or operators & and | Matlab also provides the short-circuit logical operators && and ||. They have the identical meaning as & and |, but operate somewhat more efficiently by only evaluating the second expression, if the statements logical state is not already determined fully determined by the first expression. They also work on different variables: the single operators & and | work on arrays (and scalars, which are arrays with only one entry), while the && and || operators only work on scalars. (x < y) && (x < z) Is x smaller than y and is x smaller than z? (x < y) || (x < z) Is x smaller than y or x smaller than z? 50.2 Conditional statements Conditional statements offered by Matlab are the if-statement, the if-else-statement, and the switch- statement. We only consider the former two here. if-statements and if-else-statements The if-statement allows for deciding whether another statement or a group of statements is executed or not. The general form of the if-statement is if condition action end In the above, a condition is a logical expression that is true and false. The action is a statement, or a group of statements, that will be executed, if the condition is true. If the condition is false, the action will not be executed. The action can be any number of statements until the reserved word end. The action is usually indented for easy code readability. For example, the following if-statement checks to see whether the value of a variable called num is negative. If it is, the value is changed to zero, otherwise, nothing happens: if num < 0 num = 0; end This may be used, for example, to ensure that the square root function is not used on a negative number. The if-statement as introduced above decides whether a given action is executed or not. Choosing between two actions, or choosing among several actions can be accomplished using if-else and nested if-else statements. The if-else statement is used to choose between two statement or sets of statements. Its general form is: if condition action 1 else action 2 end First, the condition is evaluated. If it is true, then the set of statements designated as action 1 is executed, and that is the end of the if-else statement. If instead, the condition is false, the second set of statements designated as action 2 is executed and that is the end of the if-else statement. The first set of statements is called the action of the if clause, it will always be executed if the condition is true. The second set of statement is called the action of the else clause, it is what will be executed if the expression is false. One of these action, and only one, will be executed which one depends on the value of the condition. As an example, the following code determines and prints whether or not a random number in the range from 0 to 1 is less than 0.5 if rand < 0.5 disp('Random number was less than 0.5') else disp('Random number was not less than 0.5') end The if-else statement is used to choose between two actions. To choose among more than two actions, if- else statements can be nested. For example, consider implementing the following continuous mathematical function ( 1 x < −1 f : R ! R; x 7! f(x) := (50.1) x2 x ≥ −1 ^ x ≤ 2 The value of y is based on the value of x, which can be in one of the possible ranges. Determining the range can be accomplished with three separate if-statements as follows: if x < -1 y = 1; end if x >= -1 && x <= 2 y = xˆ2; end ifx>2 y = 4; end As the three possibilities are mutually exclusive, the value of x can be determined using three separate if- statements. However, this is not very efficient: all three logical expressions must be evaluated, regardless of the range in which x falls. For example, if x is less than -1, the first expression is true and 1 would be assigned to y. However, the two expressions in the next two if-statements are still evaluated, although it is clear that they will be false, and y has already been assigned a value. Instead of writing it this way, the statements can be nested so that the entire if-else statement ends when an expression is found to be true if x < -1 y = 1; else % if we are here, x must be >= -1. we use an if-else statement to % choose between the remaining two ranges if x <= 2 y = xˆ2; else % no need to check anything, if we are here, x must be > 2 y = 4; end end By using nested if-else statements to choose from among the three possibilities, not all conditions must be tested as they were in the previous example. In this case, if x is less than -1, the statement to assign 1 to y is executed, and the if-else statement is completed so no other conditions are tested. If, however, x is not less than -1, then the else-clause is executed. If the else-clause is executed, then it is already known that x is greater than or equal to -1 so that part does not need to be tested. Instead there are only two remaining possibilities. So, the action of the else clause was another if-else statement. Although it is long, all of the above code is one if-else statement, a nested if-else statement. It is actually an example of a particular kind of nested if-else statement called a cascading if-else statement. This is a type of nested if-else statement in which the conditions and actions cascade in a stair-like pattern: if x >= 0 ifx<4 disp('a') else disp('b') end else disp('c') end In addition to nested if-else statements, Matlab offers another method for choosing from multiple lines of actions, using the elseif-clause. For example, if there are n choices, the following general form can be used: if condition 1 action 1 elseif condition 2 action 2 elseif condition 3 action 3 . else action n end The previous example can be rewritten using the elseif clause, rather than nesting if-else statements, as follows: if x < -1 y = 1 elseif x <= 2 y = xˆ2 else y = 4 end Note that in this example we only need one end. Thus, there are three ways of accomplishing the original task: using three separate if-statements, using if-else statements, and using and if-statement with elseif clauses, which is presumably the simplest. 50.3 Loops We next consider statements that allow other statements to be repeated. The statements that do this are called loop-statements. There are two basic loops in programming: counted loops and conditional loops.