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 , (sections 7.1 – 7.2.2, 7.4, 7.4.1)
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
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”
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
Note – value and class
More examples: expressionresult 5 < 71 [ 3, 5, 2 ] > = [ 1, 0, 12 ]1 1 0 max( 1:6 ) < = 7 1 [3, pi, -12 ] > 'Tom' = = 'Bob'0 1 0 'Tom' = = 'm'0 0 1 Note – arrays and strings need to be the same size
Notes: – Can compute using the result: e.g. “how many of a particular letter in a state name?
Don’t confuse = = and = Round off errors can impact ~ = sind(0) = = 01 sind(180) = = 00 instead, test for small values abs( sind(180) ) < = eps1
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
Basic operators: and & or | xor not ~ ABA&BA|BA|Bxor(A,B)~A~A “truth table”“unary” operator
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)
Array example: Score = [ 70, 55, 88, 98, 80, 73, 90 C = (Score > 70) & (Score < 81) C = [ ] Useful in counting how many entries satisfy a condition: B_grades = sum( Score 80 )
Text examples: 'Tom'= ='m' | 'Tom'= ='o' name = input('enter name','s'); name = = 'Tom' | name = = 'Bob' Rolling dice: roll = sum(ceil(6*rand(1,2))); roll = = 7 | roll = = 11
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( )
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 (|)
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
“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
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
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
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
Example – Write a script to put 2 numbers in numerical order:
Loops Commands to repeatedly execute certain blocks of code Two types in Matlab: – for – while this week
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
Example – collect 7 digits of a telephone number and store in an array: 7 repetitions since the array is [ ] digit cycles through the 7 values to create the 1 by 7 array “number”
Example – calculating interest for 10 years: command num2str converts numerical variables to string variables for concatenating with other strings
Example – implement a count down timer (in seconds):
Example – a general vector for array:
Example – a matrix for array:
Example – even a string array:
Errors in Your Scripts Syntax errors: Note – red text = bad newsBut tells you where
Run-time errors: inf or NaN results Note – black text = okay, just a warning
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
Matlab Data Files (not in the text) Types: –.asv = auto save – ascii = regular text files –.mat = Matlab’s proprietary format (multiple variables)