Control Statements ELEC 206 Prof. Siripong Potisuk 1 Objectives Learn how to change the flow of execution of a MATLAB program through some kind of a decision-making process within that program The program makes these decisions by comparing values of some variables The comparison is done by using a combination of relational & logical operators 2 1
Controlling Flow of Execution Constructs that allow MATLAB to decide whether or not to execute some code that follows the statement or to repeat certain groups of statements Repetitions or loops: 1) for- 2) while- Decision-making: 1) if- 2) if-else- 3) if-elseif-else- 4) Switch case Jumping or Skipping: 1) break 2) continue 3 Flow Chart A diagram that shows the step-by-step flow of execution. It is particularly useful for showing how control statements work. Some common flowchart symbols are represents a sequence of commands represents an if-statement shows the direction of code execution 4 2
Repetitions or Loops A loop executes one set of commands repeatedly. MATLAB has two ways to control number of times loop executes commands - Method 1: for.. loop executes commands a specified number of times - Method 2: while.. loop executes commands as long as a specified expression is true 5 Loop index variable can have any variable name (usually i, j, k, m, and n are used) Avoid using i and j when working with complex numbers. In general, loop body should not change value of k Each for command must have an command 6 3
1. The loop sets k to f, and executes the loop body, i.e., commands between the for and the commands, 2. The loop then sets k to f+s and re-executes the body 3. The process repeats itself until k>t,at which point the program continues with commands that follow the command 7 f and t are usually integers while s usually omitted. If omitted, loop uses an increment of 1 The increment s can be negative e.g., k=25: 5:10 produces four passes with k = 25, 20, 15, 10 If f=t, the loop executes once If f>t and s>0, or if f<t and s<0,loop not executed Value of k not displayed automatically. To display the value in each pass, type k as one of commands in loop body (sometimes useful for debugging) When loop s, k has the value last assigned to it 8 4
If k, s, and t are such that the last value of k cannot be equal to t, then - for s positive, the last pass is one where k has largest value smaller than t. For example, k=8:10:50 produces five passes (k = 8,18,28,38,48) - for s negative, last pass is one where k has smallest value larger than t k can also be assigned specific values (typed as a row vector) For example: for k = [7 9 1 3 3 5] 9 EXAMPLE: Show the output of the following script for k=1:3:10 k x = k^2 fprintf('after loop k = %d\n', k); Output: k = 1 x = 1 k = 4 x = 16 k = 7 x = 49 k = 10 x = 100 After loop k = 10 10 5
EXAMPLE: Write a script file using a for- loop to calculate the sum of the first n terms of the series: n (-1) k k 1 2 k k for n = 4 and 20. n = input( Enter the # of terms: ) sum = 0; for k=1:n sum = sum+(-1)^k*k/2^k; fprintf( The total sum is %f \n', sum) Output: Enter the # of terms: 4 The total sum is -0.125000 11 The while- loop used when - number of loop iterations not known - a testable condition to stop looping when it is false. Examples of test condition: - keep reading data from a file until the is reached - keep adding terms to a sum until the difference of the last two terms is less than a certain amount 12 6
1. Loop starts by evaluating conditional expression 2. If true, executes code in the loop body, then goes back to step 1 3. If false, skips code in the loop body and continue program execution with the code after the statement 13 The conditional expression must have a variable which changes its value after each pass There must be some value of the variable that makes the conditional expression false EXAMPLE: The script x = 1 while x <= 15 x = 2*x outputs x = 1 x = 2 x = 4 x = 8 x = 16 14 7
EXAMPLE: The sequence of Fibonacci numbers F [n] is a sequence of integers starting with 0 and 1, i.e., F [1] = 0 and F [2] = 1. The next number in the sequence is the sum of the previous two numbers, i.e., 0 1 1 2 3 5, 8, 13,.. (a) Derive a recursive equation that can be used to compute the sequence. (b) Write a script file using a while- loop to compute the first 25 numbers in the sequence. 15 (a) F[n] = F [n 1] + F [n 2], n 3 (b) N = input( Enter the # of terms: ) F(1) = 0; F(2) = 1; k = 3; while k <= N F(k) = F(k-1)+F(k-2); k = k+1; fprintf( The first %d terms of the Fibonacci sequence is \n',n) fprintf( %d \n, F) 16 8
Output: Enter the # of terms: 25 The total sum is -0.125000 The first 25 terms of the Fibonacci sequence is 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 17 An infinite loop (also known as indefinite loop) happens if the conditional expression never becomes false, the loop will keep executing... forever! If there is no output from the loop (as if often the case), it will look like MATLAB has stopped responding If your program gets caught in an indefinite loop, activate (i.e., put the cursor in) the Command Window and press CTRL+C 18 9
Common Causes of Indefinite Loops 1. No variable in conditional expression d1 = 1; d2 = 10; d3 = 0; d1 and d2 never change while d1 < d2 fprintf('distance = %d\n', d3); 2. Variable in conditional expression never changes min_d = 42; D_Increment = 0; D = 0; while D < min_d D = D + D_Increment; Typo should be 10 19 3. Wrong variable in conditional expression changed Min_D = 42; delta = 10; D = 0; while D < min_d min_d = min_d + delta; Typo should be D 4. Conditional expression never becomes false Min_D = 42; x = 0; y = 0; while -sqrt(x^2+y^2) < min_d x = x + 1; y = y + x; Typo shouldn't be any negative sign in front of sqrt 20 10
Conditional Statements A construct that allows MATLAB to decide whether or not to execute some code that follows the statement Four general forms if- if-else- if-elseif-else- switch case 21 Conditional expression true MATLAB execute code segment between the if and statement conditional expression false MATLAB skips the code segment between the if and statement Then, it continues executing the code after the -line 22 11
This construct executes one section of code if a condition is true and a different section of code if it is false. 23 24 12
if-elseif-else- structure chooses one of three or more sections of code to execute Can have as many elseif statements as necessary Can omit else statement If omitted and no match to if- or elseifstatements, no code in structure gets executed An easier-to-read alternative structure to the if-elseif-else- structure Choose code to execute based on value of scalar or string, not just true/false 25 26 13
The switch-case structure When the switch-expression is evaluated, If value is equal to value1, executes Group 1 all commands then executes code after statement If value is equal to value2, same as above but Group 2 commands only Etc. 27 The switch-case structure If switch-expression not equal to any of values in case statement, commands after otherwise executed. If otherwise not present, no commands executed If switch expression matches more than one case value, only first matching case executed Comparisons of text strings (within single quotes) are case-sensitive. 28 14
Nesting If a loop or conditional statement is placed inside another loop or conditional statement, the former are said to be nested in the latter Most common to hear of a nested loop, i.e., a loop within a loop Often occur when working with twodimensional problems Each loop and conditional statement must have an statement 29 30 15
The break Command When inside a loop (for and while), break terminates execution of loop - MATLAB jumps from break to command of loop, then continues with next command (does not go back to the for or while command of that loop). - break s whole loop, not just last pass If break inside nested loop, only nested loop terminated (not any outer loops) 31 The break Command break command in script or function file but not in a loop terminates execution of file break command usually used within a conditional statement. If In loops, provides way to looping if some condition is met 32 16
Trick "1" is always true so it makes loop iterate forever! while( 1 ) name = input( 'Type name or q to quit: ', 's' ); if length(name) == 1 && name(1) == 'q' break; Only way to exit loop! else fprintf('your name is %s\n', name); If user entered only one letter and it is a "q", jump out of loop; Otherwise print name 33 The continue command Use continue inside a loop (for- and while-) to stop current iteration and start next iteration continue usually part of a conditional statement When MATLAB reaches continue it does not execute remaining commands in loop but skips to the command of loop and then starts a new iteration 34 17
for ii=1:100 if rem( ii, 8 ) == 0 count = 0; fprintf('ii=%d\n',ii); continue; % code % more code Every eight iteration reset count to zero, print the iteration number, and skip the remaining computations in the loop 35 18