EG-127J Introduction to MATLAB for Engineers Dr. Andrew Tappenden MEng, PhD, FHEA a.c.tappenden@Swansea.ac.uk Lecture 3: Control Structures Year 1 Mechanical, Civil & Electrical Engineering CONTROL STRUCTURES ‘FOR’ LOOPS and ‘WHILE’ LOOPS When coding, the sequences of calculations are not only linear, where one evaluation is performed, the next line is then performed and so on until it finishes. There are many instances in which the same calculation is required to be performed again and again, repeating either for a certain number of iterations before proceeding, OR repeating until a certain criterion is met before proceeding. In MATLAB, these looping functions are called a ‘for’ loop or a ‘while’ loop respectively. x = x + 1 Define x=0 is x > 3 Start False Output x value End Loop True Flowchart Example ‘while’ loop Example: Code Flowchart to increase value of x until > 3. Loops An example of using a ‘while’ loop was shown in the 1st lecture in the flow diagram example. For Loop ‘FOR’ Loop Flowchart Example Define Loop Counter ‘i’ and vector limits Output calculations Perform Calculations in loop is i = i (end) i = i + 1 i = i(1) False True ‘for’ Loop A ‘for’ loop, is a section of code that cycles through repeatedly for a pre- determined number of cycles. When initialising a ‘for’ loop, a loop counter is created. In the flowchart, the loop counter has been named ‘i’ (a loop counter is just a variable, use MATLAB naming conventions). The loop counter is assigned to a vector (MUST ONLY be integers). The vector integers are the values which the loop counter will be assigned to for each successive loop cycle (until the loop section end is reached). At the end of the code section loop, MATLAB checks to see if the ‘for’ loop needs to finish, or re-start. It does this by checking the current value of the loop counter, compared to what the final value of the loop counter vector will be. If the loop counter is NOT equal to the FINAL loop counter vector value, the loop re-starts, the loop counter CHANGES to the next integer value in the vector, and the loop contents are calculated. If the loop counter EQUALS the max value in the vector, the loop exits. Example: ‘for loop’ layout For Loop ‘FOR’ Loop Flowchart Example Define Loop Counter ‘i’ and vector limits Output calculations Perform Calculations in loop i = i + 1 i = i(1) False True ‘for’ Loop The loop counter is assessed for when to exit the loop, but this is not its only use in a ‘for’ loop. As the loop counter is fundamentally a variable, it can be used in the calculations inside the loop. is i = i (end) Example: ‘for loop’ In this example, we can see that when ‘i’ is typed in the loop to be displayed for each loop cycle, the value of ‘i’ is overwritten each cycle, and when the loop exits, ‘i’ is equal to a single integer value (the final vector value). Remember: 1:5 is the vector [1 2 3 4 5] For Loop As the loop counter increases each cycle iteration in integer form, a loop counter is often used to reference the index of a variable during calculations. Example 1: ‘for’ loop using index In this example the loop counter ‘i’ has been assigned to 2 variables A and B. ‘i’ is also used to reference the index of B so that the calculations of each loop cycle are stored, and NOT overwritten. By using the loop counter as the index for B (B(i)), this ensures that in the 1st cycle when ‘i’ = 1, B(1) = i and when the 2nd cycle occurs, B(2) = i and so on throughout the loop cycles. On completion of the loop cycles, we see B is now a vector the length of the loop counter vector, and A (assigned as i) is a single integer value (having been overwritten each loop). Example 2: ‘for’ loop using index For Loop In this example C and D have been initialised outside of the ‘for’ loop. This is because if they are initialised inside the loop, each time the loop cycle re-starts, the values of C and D would be re-initialised, and consequently erase any of the previous cycles calculations. Without using the loop counter as the index for C, as the cycles iterate, C is overwritten; but by using its own variable in the calculation (C = C+i), the previous value can be brought into the next cycle and in this case add the value of i. For ‘D’ however, this example is adding an integer of 1 to the i counter for the D index assigning. This means that the 1st cycle of calculations is set to the 2nd index of D, and with D(i) being used in the calculation, this means the previous value of D is used in the assigning +i. 1st Cycle 5th Cycle 3rd Cycle 4th Cycle 2nd Cycle While Loop ‘WHILE’ Loop Flowchart Example Initialise ‘condition’ variable while ‘condition’ meets criterion, continue loop. Perform Calculations in loop does ‘condition’ meet criterion False True Output calculations ‘while’ Loop A ‘while’ loop, is a section of code that cycles through repeatedly for an undetermined number of cycles, until a condition criterion is met. When initialising a ‘while’ loop, a condition variable needs to be set, to evaluate against a specified criterion. At the end of each cycle the condition is checked against the criterion, to assess whether to exit the ‘while’ loop or to re-start and re-calculate the loop contents. Example: ‘while’ loop not meeting criterion While Loop Example: ‘while’ loop x has been initialised to equal 10 before the while loop. If initialised inside the ‘while’ loop, ‘x’ would reset each cycle to 10, and the loop execution will not stop. In each loop, x has 2 subtracted and at the end of the loop cycle, if x >5, the loop cycles and re-calculates, if x≤5 the loop exits. When a ‘while’ loop is used in code, it is essential that IF the contents of the loop have to be calculated, the condition variable MUST meet the while loop criterion. Otherwise the ‘while’ loop will be skipped entirely. (See example above). Initialised x=1.6 (less than criterion), x > 3 to enter while loop. Example: ‘while’ loop incorporating loop counter and indexing. Example: ‘while’ loop using multiple criteria While Loop Often, multiple criteria will need to be met in a calculations. In MATLAB, the logical operators are && and ||, where these represent ‘and’ (both expressions need to be met), and ‘or’ (either expression needs to be met to break the loop). If these operators are not met, they act as a ‘short circuit’ and so exit the ‘while loop’. While 3 > x ≤ 10, the while loop iterates. Loop counters can be utilised like in a ‘for’ loop, except the counter variable needs to be created specifically for the task. In this case, i = i +1 . The loop counter is then used here for indexing calculations. Example: Never-ending ‘while’ loop Example: ‘break’ a loop Stopping a Runaway Loop REMEMBER: To Cancel MATLAB running operations: Ctrl + C Sometimes a ‘while’ loop will accidentally be coded that will never end. (x will always be >3). In these cases, MATLAB will only stop through ‘Force Stopping’ the code. When coding using loops, for either ‘for’ loops or ‘while’ loops, there are many times that being able to stop or ‘break’ a cycling loop is beneficial. This can be if the calculations are not going to stop, or if a requirement is met. By using the conditional statement: – ‘if [condition]’ break ‘end’ This immediately exits the loop. Nesting Loops In the example shown, there is an outer loop, which runs from loop counter ir = 1 to ‘rows’ (defined variable), and there is an inner loop which has a loop counter ic which loops from ic=1 to ‘columns’ (defined variable). Code and flowchart algorithm: MATLAB enters the outer loop, (ir = 1). MATLAB enters inner loop (ic =1). The fprintf displays a star, ic counter increases (ic = ic+1) until ic = ic(end). Exits inner loop New line in command window Outer loop counter increases (ir = ir+1) until ir = ir(end). End code A ‘nested’ loop is where a looping section of code is placed within another looping code section. EXAMPLE: Nested Loops EXAMPLE: Flowchart Nesting Loops EXAMPLE: Nested Loops Shows the value of i and j and calcs through successive loop cycles. 1st 2nd 3rd 4th 5th 6th 7th 8th 9th( i= 1 ; j = 1: 3) (i = 2 ; j = 1: 3) (i = 3 ; j = 1: 3) In the previous example, the nested loops simply printed to the command window. An important use of nested loops however, is to use the loop counters to store calculations using indexing. As the loop counters for the inner and outer loops cycle, the counter values are used within parentheses of the variable used to store calculations. This ensures that calculations are not overwritten during each successive loop cycle. In this example, the value of the calculation ‘A’ is displayed, along with a printing statement, showing the outer loop counter variable value and inner loop counter variable value. Remember for this example: A(i,j), i is the row index j is the column index. CONTROL STRUCTURES: CONDITIONAL STATEMENTS ‘IF’, ‘ELSEIF’ and ‘ELSE’ Conditional Statements In coding it is commonplace to have coding that needs to be implemented ONLY if a certain criterion is met. For this we use a control structure called conditional statements (‘if’, ‘elseif’ and ‘else’). The conditional statement ‘if’ is similar to some properties of a ‘while’ loop. A ‘while’ loop will execute a section of code in cycles until a condition is no longer true, whereas the conditional statement ‘if’ will execute a section of code and implement it ONCE if a condition is true. Conditional statements will often be used inside loop structures, allowing code to adapt based on the calculations themselves. Sometimes different sections of code will need to be run through based on various criteria. Although separate ‘if’ statements can be used, this is inefficient and messy. If additional condition options are valid, the ‘elseif’ conditional statement is used. ‘elseif’ expressions can be used one after another, but if there reaches a point where there is only a single option remaining, the ‘else’ structure would be used but without and conditions associated. Conditional Statements Example: ‘if’, ’elseif’ and ‘else’, In this example, variable ‘A’ is assigned to a random number between 0 and 1 (using the function ‘rand()’). We want to print to the command window a text string stating whether A is greater than 0.5, A is between 0.2 and 0.5, or A is between 0 and 0.2. To do this the ‘if’ ‘elseif’ and ‘else’ statements are used to separate the fprintf() text strings, so that if the condition for the relevant conditional statement is true the relevant fprintf() statement is run. N.B. When using a single condition, as with this example, the ORDER in which the statements are checked by MATLAB MATTERS! If the A≥0.2 was placed at the ‘if‘ statement, and the A>0.5 at the ‘elseif’; because the ‘if’ statement covers ALL values greater than 0.2, MATLAB will never pass into the ‘elseif’ A>0.5 section of code. Conditional Statements Example: ‘if’, ’elseif’ and ‘else’, using double conditions. If more precise defining of the conditional statements is required, the logical operators ‘&&’ and ‘||’ can be used to incorporate multiple conditions for each section of code. As with utilising the logical operators with ‘while’ loops, the ‘&&’ relates to the use of scalar ‘AND’ statements and ‘||’ relates to scalar ‘OR’ statements. If vectors are used ‘&’ and ‘|’ are used. In this example, for each set of conditional statements, two conditions are set. – By using multiple conditions, the available outcomes have become more restricted, and thus the order of these conditionals are less relevant. In the previous example, fprintf() only printed pre-defined strings. – Here, the variable ‘A’ is automatically printed to 4 decimal places alongside some pre-defined strings of text (with the cursor forced to a new line using n)