Date post: | 21-Dec-2015 |
Category: |
Documents |
View: | 220 times |
Download: | 1 times |
Week 7 - Programming I
• Relational Operators• A > B
• Logical Operators• A | B
• For Loops• for n = 1:10
– commands
• end
Week 7 - Programming I
• Introduce programming:– “scripts” and “functions” are programs of sequentially
evaluated commands
• Today, extend features to:• additional operators
• branches to control operations
• loops to repeat operations
• Textbook chapter 7, (sections 7.1, 7.2.1, 7.2.2, 7.4.1, 7.6)
Relational Operators
Used to compare A and B: A op B• A and B can be:
– Variables or constants or expressions to compute
– Scalars or arrays (watch the sizes on arrays!)
– Numeric or string
• Result is true (1) or false (0) – perhaps an array• Operators: > > = = =
< < = ~ =
• 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 ~ = sin(0) = = 0 1
sin(pi) = = 0 0
instead, test size
abs(sin(pi)) < = eps 1
0 2 4 6 8-1
-0.5
0
0.5
1
Logical Operators
Typically, used to combine A and B: A op 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 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: expression result(5<7)&(11>9) 1 'Tom'= ='m' | 'Tom'= ='o' 0 1 1
• Also consider: name = input('enter name','s');name = = 'Tom' | name = = 'Bob'
orroll = sum(ceil(6*rand(1,2)));roll = = 7 | roll = = 11
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
Example 1 – 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 2 – output a warning if the variable x is negative (note that there is no “else” portion in this test):
x = … { computed somehow };
if x < 0
disp(‘Warning: negative value’)
end
no else component
Example 3 – ask if a plot should be drawn:
x = input(‘Plot now? ‘,’s’);
if x = = ‘yes’ | x = = ‘YES’
plot( ….. )
end more complicated expression
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
Homework revisited – collect 7 digits of a telephone number and store in an array:
for digit = 1:7
number(digit) = input('enter value ');
end
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 1 – calculating interest for 10 years:
value = 1000;
for year = 1:10
value = value * 1.08;
fprintf('$ %6.2f after %2d years\n', value,year)
end
no need for a counter variable!year takes on the values 1 through 10
Example 2 – implement a count down timer
(in seconds):
time = input(‘how long? ‘);
for count = time:-1:1
pause(1)
disp([ num2str(count),’ seconds left’])
end
disp(‘done’)
Example 3 – a general vector for array:
for x = [ 8 7 4 5 8 0 2 ] disp(['dial ', num2str(x) ]) pause(1)end
Example 4 – a matrix for array:
board =(2*(rand(3,3)>.2)–1).*(rand(3,3)>.5)for x = board xend
Example 5 – even a string array:
for x = 'EGR106' disp(x)end
Early Termination of Loops
Use the break command:
for variable = {array of length n} …..
breakend
Terminates the loop
Example – Hi-Lo: a guessing game with feedback
select hidden number
input guess
correct?
yes
noprovide hi/lo feedback
5 tries?
yesno
win
lose
% HI-LO numb = round ( 100 * rand (1) ); for count = 1:5 guess = input('guess my number '); if guess = = numb
disp( 'You got it !!!' ) break
end if guess > numb disp('you are too high') else disp('you are too low') end if count = = 5
disp('Sorry, you lose! ') endend
Example – calculating interest until the amount doubles using a for loop:
value = 1000;
for year = 1:1000
value = value * 1.08;
fprintf('$ %6.2f after %2d years\n', value,year)
if value >= 2000
break
end
end
will calculate up to 1000years, if necessary
if condition decideswhen to terminate loop