Lecture 3

Lecture 3 - Lecture 3. Control ­Flow Statements ...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Lecture 3. Control ­Flow Statements While Matlab can be used as a calculator, it is still fundamentally a programming language. The building blocks of any programming language are the control ­flow statements. This lecture will cover the following topic:  ­ conditional statements  ­ relational operators and logical operators  ­ while loops  ­ for loops We will spend most of this lecture working in the script window. To create a new script, enter: >> edit name_of_file Let’s first introduce some things that we will be using through out this lecture. Character Arrays: Matlab allows you to store a string of text inside a variable. We have seen an example of this when we used the disp() command. The text that we enclosed the single quote ‘ ‘ is actually a character array. To assign a character array to a variable, enter the following command: >>name_of_variable = ‘text to be saved’ Example: >> text = 'hello world!' text = hello world! >> disp(text) hello world! The reason why it is called a character array is because the text is stored in a 1 x n row matrix. To see this, try the following: Example: >> text(1,1) ans = h >> text(1,2) ans = e An alternative way to refer to each character in the array is to use the following: Example: >> text(1) ans = h >> text(2) ans = e User Inputs: To get input from the user, we use the input() function. Example: >> x = input('Please enter a number: ') Please enter a number: 10 x = 10 The input() function does two things: 1) It displays whatever that is enclosed within the single quotes 2) It asks the user for an input and saves it in a variable To save a character array into a variable, we need to use an alternative form of the input() function, with a ‘s’ as the extra parameter: Example: >> text = input('Enter a string: ', 's') Enter a string: hello! text = hello! Note: The variable x = 5 and x = ‘5’ are not the same! The first one assigns the value 5 to x, and the second one assigns the character ‘5’ to x. You cannot use the character ‘5’ when doing a computation! Example: >> x = '5'; >> x + 5 ans = 58 To convert a string to a number, use the str2num() function. Example: >> str2num(x) + 5 ans = 10 To convert a number to a string, use the num2str() function. This is useful when we want to concatenate some text and variable together to make an output. Example: >> str = [ 'The value of x is ', num2str(x)] str = The value of x is 5 Conditional Statements: Conditional statements are used to determine whether or not certain commands are executed based on a condition. The most basic form of a conditional statement is an if ­statement in the form of: if ( condition) some_commands_to_be_executed end If the (condition) are true, then the commands inside the if statements are executed. Otherwise, the commands will be skipped. Example: IfExample1.m % Tests if 3 is less than 4 if ( 3 < 4) disp(' 3 is less than 4!') end Command Window: >>IfExample1 3 is less than 4! (Recall that the disp() function displays whatever text that is enclosed in the single quotes) Before we continue our discussion of control ­flow statements, we will take a moment to explore some relational operators and logical operators. Relational Operators and Logical Operators: When Matlab evaluates a condition, it will either return “true,” which in Matlab is symbolized by “1”, or “false”, symbolized by “0”. Relational Operators: Relational operators are used to compare two or more values. The relational operators that are in Matlab are:  ­ < less than  ­ <= less than or equal to  ­ == equal to  ­ > greater than  ­ >= greater than or equal to  ­ ~= not equal to When using the relational operators, Matlab will evaluate the condition and return either a “true” or a “false” value. Example: As an illustration of how “true” and “false works in Matlab, enter the following command: >> 5 < 8 ans = 1 As you can see, the condition is true, and Matlab displays “1”. >> 2 > 5 ans = 0 The condition is false, and Matlab displays “0”. Note: Do not confuse the assignment operator ‘=” with the comparison operator “==”!!! Logical Operators: Similar to relational operators, logical operators are used to compare/test various conditions. Logical Operator Symbol Description and & TRUE only if both conditions are true or | TRUE if either conditions are true not ~ TRUE if the condition is FALSE Example: >> 5 < 6 & 4 >8 ans = 1 >> 7<= 10 | 9 < 5 ans = 1 Note: Matlab evaluates a logical expression from left to right, and it evaluates the relational operators before the logical operators. The precedence that Matlab uses to evaluate the expressions is as follows: >> help precedence PRECEDENCE Operator Precedence in MATLAB. MATLAB has the following precedence for the built ­in operators when evaluating expressions (from highest to lowest): 1. transpose (.'), power (.^), complex conjugate transpose ('), matrix power (^) 2. unary plus (+), unary minus ( ­), logical negation (~) 3. multiplication (.*), right division (./), left division (.\), matrix multiplication (*), matrix right division (/), matrix left division (\) 4. addition (+), subtraction ( ­) 5. colon operator (:) 6. less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), equal to (==), not equal to (~=) 7. element ­wise logical AND (&) 8. element ­wise logical OR (|) 9. short ­circuit logical AND (&&) 10. short ­circuit logical OR (||) Consider the following expression: >>a == b & c ==d | e == f The expression will be evaluated as >>( ( (a == b) & (c == d) ) | (e == f) ) Comparing String/Character Arrays: It is rather tricky trying to compare two character arrays. If we were to try to compare two character arrays like the following: Example: >> 'YES' == 'NO' ??? Error using ==> eq Matrix dimensions must agree. We get an error because each array is a matrix, and to compare two matrices, they must be of the same dimension. Instead of using == to compare two character arrays, use strcmp() instead. Example: >> strcmp('YES', 'NO') ans = 0 Conditional Statements (cont.): Now that we understand what relational and logical operators are, we can use them in our control ­flow statements. Example: IfExample2a.m % Display an output when x is less than 20 if (x < 20) disp('x is less than 20!') end Command Window: >> x = 10; >> IfExample2a x is less than 20! IfExample2b.m % Display an output if x is less than 20 and y is greater than 5 if ( x < 20 & y > 5) disp('x is less than 20 and y is greater than 5!') end Command Window: >> x = 10; >> y = 12; >> IfExample2b x is less than 20 and y is greater than 5! In addition to the if statement, we can add an elseif statement after to test for an alternative condition. You can add as many elseif statements as you want. Example: IfExample3.m % Test whether or not x is less than 5 or greater than 6 if (x < 5) disp('x is less than 5!') elseif (x > 6) disp('x is greater than 6!') end Command Window: >> x = 10; >>IfExample3.m x is greater than 6! Notice how we don’t have a case where x = 6. If we would like to have a default case that executes if none of the if/elseif statements execute, we add an else statement at the end. Example: IfExample4.m % Test whether or not x is less than 5 or greater than 6 % or x is equal to 6 if (x < 5) disp('x is less than 5!') elseif (x > 6) disp('x is greater than 6!') else disp('x is equal to 6!') end Command Window: >> x = 6; >>IfExample4 x is between 5 and 15 The general form of a if statement is: if (condition) statements elseif (condition) statements elseif (condition) statements ? else statements end where the elseif and else statements are optional. Note: Do not forget the “end” statement at the end! While Loops: Sometimes we want to repeat the execution of some commands until a condition is reached. To do this, we use a while ­loop; while (condition) statements end Example: To display the numbers 1 through 9: WhileLoop.m % Display the values 1 through 9 x = 1; while (x < 10) disp(x) x = x + 1; end Command Window: >>WhileLoop 1 2 3 4 5 6 7 8 9 The while ­loop consists of four parts: 1) assign an initial condition: x = 1 2) a condition to be tested: x < 10 3) some commands to executed if the condition is true: disp(x) 4) update the condition: x = x + 1 If part 4) is missing or is incorrect, the while loop would continue to run forever, resulting in an infinite loop, which is disastrous and should be avoided! (Unless you are purposely doing it.) Break and Continues However, sometimes you would like to create a loop that continues until the user enters a specific input to exit the loop. In such case we would use a break to exit the loop. A break forces the execution to exit the loop that the program is currently in. Example: InfiniteLoop.m % Create an while-loop that continues to ask the % user for a positive input until the user enters a % non-positive input while (1) x = input('Enter a positive value: '); if ( x <= 0) disp ('You have entered a non-positive value. The loop will now terminate.'); break end disp('You have entered: '); disp(x); end Command Window: >>InfiniteLoop Enter a positive value: 5 You have entered: 5 Enter a positive value: 2 You have entered: 2 Enter a positive value:  ­4 You have entered a non ­positive value. The loop will now terminate. The continue command does the opposite of break. Instead of jumping out of the loop, it restarts the loop. Example: ContinueExample.m % Printes out 1 through 9, but skips 5 by using % a continue statement to bypass the disp() function x = 1; while (x < 10) if ( x == 5) x = x + 1; continue; end disp(x) x = x + 1; end Command Window: >> ContinueExample 1 2 3 4 6 7 8 9 Notice how we have skipped 5. When x == 5 in the while loop, x is updated to 6, and continues jumps the execute to the beginning of the loop again and bypasses the disp(x) function. For Loops: A for ­loop is similar to a while ­loop, except it explicitly keeps track of the loop ­ control variable, which controls how often the commands have to be repeated. The general form of a for ­loop is: for variable = start:step:end commands end Example: ForLoop.m % Prints out the values 1 through 9 using a for loop for x = 1:9 disp(x); end Command Window: >>ForLoop 1 2 3 4 5 6 7 8 9 10 Nested Loops We can create nested loops by placing one loop inside of another loop. Example: NestedLoop.m % A nested-for loop that displays the outer x, then the % inner loop y and then their sum, x + y for x = 0:3 disp(['The current x is ', num2str(x)]) for y = 0:3 disp(['The current y is ', num2str(y)]) disp(['x + y is ', num2str(x + y)]) end disp(' ') end Command Window: >>NestedLoop The current x is 1 The current y is 1 x + y is 2 The current y is 2 x + y is 3 The current y is 3 x + y is 4 The current x is 2 The current y is 1 x + y is 3 The current y is 2 x + y is 4 The current y is 3 x + y is 5 The current x is 3 The current y is 1 x + y is 4 The current y is 2 x + y is 5 The current y is 3 x + y is 6 Note: Make sure to close each loop with an end or else you will be in trouble! ...
View Full Document

This note was uploaded on 11/03/2011 for the course MATH 1090 taught by Professor Greenwood during the Spring '08 term at MIT.

Ask a homework question - tutors are online