Chapter 4 Programming with Matlab. Relational Operators Logical Operators and Functions Conditional Statements Loops Homework

Chapter 4 Programming with Matlab • • • • • Relational Operators Logical Operators and Functions Conditional Statements Loops Homework Relational O...
Author: Jean Goodwin
2 downloads 0 Views 121KB Size
Chapter 4 Programming with Matlab • • • • •

Relational Operators Logical Operators and Functions Conditional Statements Loops Homework

Relational Operators • Matlab has six relational operators to make comparisons between arrays [< less than; greater than; >=greater than or equal to; == equal to; ~= not equal to] • The relational operators have equal precedence among themselves and Matlab evaluates them in order from left to right. z = 5 > 3 ~= 1 is the same as z = (5 > 3) ~= 1

Logical operators Table 4.3–1 Operator

Name

Definition

~

NOT

~A returns an array the same dimension as A; the new array has ones where A is zero and zeros where A is nonzero.

&

AND

A & B returns an array the same dimension as A and B; the new array has ones where both A and B have nonzero elements and zeros where either A or B is zero.

|

OR

A | B returns an array the same dimension as A and B; the new array has ones where at least one element in A or B is nonzero and zeros where A and B are both zero.

Logical Operators: Examples Using Arrays A=[4 0 7 8 0 2] ~A=[0 1 0 0 1 2] A=[0 0 3 9 5 0 7 7] ~A=[1 1 0 0 0 1 0 0] ~A returns an array the same dimension as A; 1’s where A is 0 and 0’s where A is nonzero A=[4 0 5 5 0 3] B=[0 0 7 0 2 2] A&B C=[0 0 1 0 0 1] A&B returns an array the same dimension as A and B; new array has 1’s where both A and B have nonzero elements and 0’s where either A or B is 0. A=[3 0 6 6 0 9] B=[0 0 2 0 8 8] A|B C=[1 0 1 1 1 1] A | B returns an array the same dimension as A and B; the new array has ones where at least 1 element in A or B is nonzero and 0’s where both A and B are both 0.

Order of Precedence for Operator Types First

Parentheses; evaluated starting with the innermost pair Arithmetic operators and NOT; evaluated from left to right Relational operators; evaluated from left to right Logical AND Logical OR

Second Third Fourth Fifth

THE TRUTH TABLE x

y

~x

x|y

x&y

true

true

false

true

true

true

false

false

true

false

false

true

true

true

false

false

false

true

false

false

The following Matlab session generates the truth table in terms of ones and zeros >>x = [1,1,0,0]’; >>y = [1,0,1,0]’; >>Truth _ Table = [x,y,~x,x|y,x&y] Truth _ Table = 1 1 0 1 1 1 0 0 1 0 0 1 1 1 0 0 0 1 0 0 Matlab also has many useful logical functions such as find(x) and any(x) See table 4.2-4

The find function is useful for creating decision making programs, especially when combined with the relational or logical operators. find(x)computes the array containing the indices of the nonzero elements of the array x. >>x=[5,-3,0,0,8]; y=[2,4,0,5,7]; >>z=find(x&y) Z= 1 2 5 The resulting array indicates that the first, second,and fifth elements of x and y are both nonzero. Note that this function returns the indices and not the values

The array price given below contains the price in dollars of a certain stock over 10 days. Use MATLAB to determine how many days the price was above $20.00. price = [19, 18, 22, 21, 25, 19, 17, 21, 27, 29]

>>price = [19,18,22,21,25,19,17,21,27,29] >>length(find(price>20)) ans = 6

Conditional Statements If I get a raise, I will buy a new car . (period)

If I get at least a $100 per week raise, I will buy a new car; else, I will put the raise into savings .(period)

If I get at least a $100 per week raise, I will buy a new car; else, if the raise is greater than $50, I will buy a new stereo otherwise, I will put the raise into savings .(period)

if, else, elseif statements if statement if logical expression statements end

if logical statement 1 statement group 1 if logical expression 2 statement group 2 end end

Every if statement must have an accompanying end statement. The end statement marks the end of the statements that are to be executed if the logical expression (scalar, a vector, a matrix) is true.

And you can nest if statements!!

if, else, elseif statements else statement

When more than one action can occur as a result of a decision, we can use the else and elseif statements along with the if statement.

if logical expression statements else statement group 2 end start

Logical expression

false

true Statement group 1

end

Statement group 2

Don’t forget to flow chart and use pseudocode!

if, else, elseif statements elseif statement if logical expression1 statement group 1 elseif logical expression 2 statement group 2 else statement group 3 end

The else and elseif statements may be omitted if not required. However, if both are used, the else statement must come after the elseif statement to take care of all conditions that might be unaccounted for. start

Logical Expression 1

true

false

Logical Expression 2

false

Statement group 1 Statement group 3

true Statement group 2

end

if x > 10 y = log(x) if y >= 3 z = 4*y elseif y >= 2.5 z = 2*y else z = 0 end

x no X>10?

yes y=5x z=7x

y=log(x)

no

no y>=3?

y>=2.5?

z=0

yes yes z=4y

z=2y

y,z

else y = 5*x z = 7*x end

Strings A string is a variable that contains characters. They are useful for creating input prompts and messages and for storing and operating on data such as names and addresses. To create a string variable, enclose the characters in single quotes >>name = ‘Leslie Student’ name = Leslie Student >>number = ‘123’ number = 123 Strings are stored as row vectors in which each column represents a character. For example, the variable name has one row and 14 columns (each blank space occupies one column)

Loops

A loop is a structure for repeating a calculation a number of times. Each repetition of the loop is a pass. Matlab uses two explicit loops, for (when the number of passes is known ahead of time) and while (when the looping process must terminate when a specified condition is satisfied, and thus the number of passes is not known in advance).

for Loops A simple example of a for loop is for k = 5:10:35 x = k^2 end The loop variable k is initially assigned the value 5, and x is calculated from x = k^2. Each successive pass through the loop increments k by 10 and calculates x until k exceeds 35. Thus k takes on the values 5, 15, 25, and 35, and x takes on the values 25, 225, 625, and 1225. The program then continues to execute any statements following the end statement.

Flowchart of a for Loop. Figure 4.5–1

Note the following rules when using for loops with the loop variable expression k = m:s:n: • The step value s may be negative. Example: k = 10:-2:4 produces k = 10, 8, 6, 4. • If s is omitted, the step value defaults to 1. • If s is positive, the loop will not be executed if m is greater than n. • If s is negative, the loop will not be executed if m is less than n. • If m equals n, the loop will be executed only once. • If the step value s is not an integer, round-off errors can cause the loop to execute a different number of passes than intended.

while Loops The while loop is used when the looping process terminates because a specified condition is satisfied, and thus the number of passes in not known in advance.

start

Flowchart of the while loop Logical expression

true Statements which increment the loop varialble

end Statements following the end statement

false

while logical expression statements end

For the while loop to function properly, the following two conditions must be met: 1. The loop variable must have a value before the while statement is executed. 2. The loop variable must be changed somehow by the statements.

while Loops The while loop is used when the looping process terminates because a specified condition is satisfied, and thus the number of passes is not known in advance. A simple example of a while loop is x = 5; while x < 25 disp(x) x = 2*x - 1; end The results displayed by the disp statement are 5, 9, and 17.

Another View x = 5;k = 0; while

x < 25

k = k + 1; y(k) = 3*x; x = 2*x-1; end The loop variable x is initially assigned the value 5, and it keeps this value until the statement x = 2*x - 1 is encountered the first time. Its value then changes to 9. Before each pass through the loop, x is checked to see if its value is less than 25. If so, the pass is made. If not, the loop is skipped.

Another Example of a while Loop Write a script file to determine how many terms are required for the sum of the series 5k2 – 2k, k = 1, 2, 3, … to exceed 10,000. What is the sum for this many terms? total = 0;k = 0; while total < 1e+4 k = k + 1; total = 5*k^2 - 2*k + total; end disp(’The number of terms is:’) disp(k) disp(’The sum is:’) disp(total) The sum is 10,203 after 18 terms.

The switch Structure The switch structure provides an alternative to using the if, elseif, and else commands. Anything programmed using switch can also be programmed using if structures. However, for some applications the switch structure is more readable than code using the if structure.

Syntax of the switch structure switch input expression string). case value1 statement group 1 case value2 statement group 2 . . . otherwise statement group n end

(which can be a scalar or

The following switch block displays the point on the compass that corresponds to that angle. switch angle case 45 disp(’Northeast’) case 135 disp(’Southeast’) case 225 disp(’Southwest’) case 315 disp(’Northwest’) otherwise disp(’Direction Unknown’) end