Presentation is loading. Please wait.

Presentation is loading. Please wait.

Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:

Similar presentations


Presentation on theme: "Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:"— Presentation transcript:

1 Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to: additional operators branches to control operations loops to repeat operations Textbook chapter 7, pages 165-179, 182-187 (sections 7.1 – 7.2.2, 7.4, 7.4.1)

2 Relational Operators – the Idea In formal English someone might ask you “Is your age greater than or equal to 21?” Answers include: – Yes, of course – Here’s my ID card – I’m 18 – I knew this would happen if I forgot my ID – No

3 Using mathematical notation, we test or compute the relation age ≥ 21 or age >= 21 And expect 1 of only 2 answers: – “Yes” or “True” – “No” or “False”

4 Relational Operators in M ATLAB A operator B A and B can be: – Variables or constants or expressions to compute – Scalars or arrays (match the sizes on arrays!) – Numeric or string Operators: >> == = << =~ = Result is true (1) or false (0) – perhaps an array

5 Note – value and class

6 More examples: expressionresult 5 < 71 [ 3, 5, 2 ] > = [ 1, 0, 12 ]1 1 0 max( 1:6 ) < = 7 1 [3, pi, -12 ] > 11 1 0 'Tom' = = 'Bob'0 1 0 'Tom' = = 'm'0 0 1 Note – arrays and strings need to be the same size

7 Notes: – Can compute using the result: e.g. “how many of a particular letter in a state name?

8 Don’t confuse = = and = Round off errors can impact ~ = sind(0) = = 01 sind(180) = = 00 instead, test for small values abs( sind(180) ) < = eps1

9 Matlab has Logical Operators as Well A operator B A and B can be: – Variables or constants or expressions to compute – Scalars or arrays, numeric or string A and B are interpreted as logical (binary): – Numeric 0 is interpreted as false – All else is interpreted as true (equal to 1) Result is true (1) or false (0) – perhaps an array

10 Basic operators: and & or | xor not ~ ABA&BA|BA|Bxor(A,B)~A~A 000001 010111 100110 111100 “truth table”“unary” operator

11 Examples: “Are you between 25 and 30 years old?” (age>=25) & (age<=30) “Is it winter?” (month==12 & day>=22) | (month==1) | (month==2) | (month==3 & day<=21)

12 Array example: Score = [ 70, 55, 88, 98, 80, 73, 90 C = (Score > 70) & (Score < 81) C = [ 0 0 0 0 1 1 0 ] Useful in counting how many entries satisfy a condition: B_grades = sum( Score 80 )

13 Text examples: 'Tom'= ='m' | 'Tom'= ='o' 0 1 1 name = input('enter name','s'); name = = 'Tom' | name = = 'Bob' Rolling dice: roll = sum(ceil(6*rand(1,2))); roll = = 7 | roll = = 11

14 Other useful logical operators: – Extend | and & from binary to arrays: any(X)all(X) – To check array size, value, and data type isempty(A) isinf(A)isnan(A) ischar(A)isnumeric(A) – To find the locations of events: find( )

15 Operator Precedence (left to right) 1. Parentheses ( ) 2. Transpose(') and power(.^) 3. Negation (-) and logical negation (~) 4. Multiplication (.*) and division (./), 5. Addition (+) and subtraction (-) 6. Colon operator (:) 7. Relational operators (, >=, = =, ~=) 8. Logical AND (&) 9. Logical OR (|)

16 Branches, Conditional Statements Commands to select and execute certain blocks of code, skipping other blocks. Three types in Matlab: – if/else – switch – try/catch this week

17 “If/Else” Use relational and logical operators to determine what commands to execute: if expression {commands if true } else {commands if false } end evaluate this use of blue in editor; also, auto indentation on commands

18 Example – output whether a variable x is positive or not: x = … { computed somehow }; if x > 0 disp('the value is positive') else disp('the value is negative or zero') end

19 Example – output a warning if the variable x is negative (note that there is no “else” portion in this example): x = … { computed somehow }; if x < 0 disp( ' Warning: negative value ' ) end the else component is not required

20 Example – ask if a plot should be drawn: x = input( ' Plot now? ', ' s ' ); if x = = ' yes ' | x = = ' YES ' plot( ….. ) end more complicated expression to evaluate

21 Example – Write a script to put 2 numbers in numerical order:

22 Loops Commands to repeatedly execute certain blocks of code Two types in Matlab: – for – while this week

23 The “for” Loop Used for a specific number of repetitions of a group of commands: for index = array { commands to be repeated go here } end Rules: One repetition per column of array index takes on the corresponding column’s values

24 Example – collect 7 digits of a telephone number and store in an array: 7 repetitions since the array is [ 1 2 3 4 5 6 7 ] digit cycles through the 7 values to create the 1 by 7 array “number”

25

26 Example – calculating interest for 10 years: command num2str converts numerical variables to string variables for concatenating with other strings

27

28 Example – implement a count down timer (in seconds):

29

30 Example – a general vector for array:

31 Example – a matrix for array:

32 Example – even a string array:

33 Errors in Your Scripts Syntax errors: Note – red text = bad newsBut tells you where

34 Run-time errors: inf or NaN results Note – black text = okay, just a warning

35 Logical errors in your program – hard to find – Example: quadratic equation solver – But x 2 +2x+1 = (x+1) 2  x = – 1 Use the built-in debugger Missing parentheses around 2*a

36 Matlab Data Files (not in the text) Types: –.asv = auto save – ascii = regular text files –.mat = Matlab’s proprietary format (multiple variables)


Download ppt "Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:"

Similar presentations


Ads by Google