Transcript

This Week

Quiz on Thursday, Kirk 212, everything from last quiz.

Team members and names due today at end of class.

Week 6 - Programming I

So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands

Today, extend features to:additional operatorsbranches to control operationsloops to repeat operations

Textbook chapter 7, pages 191-205, 208-213 (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 MATLAB

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:

expression result

5 < 7 1

[ 3, 5, 2 ] > = [ 1, 0, 12 ] 1 1 0

max( 1:6 ) < = 7 1

[3, pi, -12 ] > 1 1 1 0

'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) = = 0 1

sind(180) = = 0 0

instead, test for small values abs( sind(180) ) < = eps 1

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 ~

A B A&B A|B xor(A,B) ~A

0 0 0 0 0 1

0 1 0 1 1 1

1 0 0 1 1 0

1 1 1 1 0 0

“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 = [ 0 0 0 0 1 1 0 ]

Useful in counting how many entries satisfy a condition:

B_grades = sum( Score<91 & Score>80 )

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

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 componentis 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 toevaluate

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 agroup 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 [ 1 2 3 4 5 6 7 ]

digit cycles through the 7 valuesto create the 1 by 7 array “number”

Example – calculating interest for 10 years:

command num2str convertsnumerical variables to string variables for concatenating withother 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 news But 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 x2+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)