Download - “Operators” (i.e. “symbols”)
1
“Operators” (i.e. “symbols”)
1. Overview: Specific Symbols that Represent Specific Actions2. Arithmetic3. Relational4. Boolean5. Output values
Overview: most Operators
1. ARITHMETIC
+ Addition- Subtraction* Multiplication/,\ Division^ Exponentiation,
i.e. “To the power of”
• There are 3 primary groups of operators
One programming operator is very different from its use in math:
2
2. RELATIONAL
< strictly less than> strictly greater than<= less than or equal to>= greater than or equal to== is equal to~= is not equal to
3. BOOLEAN
&& “AND”|| “OR”~ “NOT”
= “the assignment operator”
Overview, cont.
• Operators work on operands.
3
4 * 5operands Multiplication operator
-5operand
Negative operator
Binary OperatorRequires two operands to work
Unary OperatorRequires one operand to work
Overview, cont.
• There are 2 types of operands:1. Numerical 1, 3.5, -472. Logical true, false
Arithmetic (+, -, /, *, ^, =) and relational (<, <=, >, >= ,==, ~=) operators work with numerical operands
4
kineticEnergy = 1 / 2 * mass * vel ^ 2
Assign operator: “place one or more values into memory”Arithmetic operators
Numerical Operands
Overview, cont.
• There are 2 types of operands:1. Numerical 1, 3.5, -472. Logical true, false
• Boolean (&&,||,~) operators work on logical operands
“ if this is true and this is false… do something”
5
if (it's raining outside) and (you have an umbrella)go, you won't get wet
elsestay inside!
end
True, False, 1, and 0?!
TrueFalse
10
3. Relational Operators
• Relational operators allow a comparison to be evaluated. Is thrust_a greater than thrust_b? True / False
Is surface1 equal to surface2? True / False?
Is load1 less than or equal to load2? True / False?
• Examples:
7
thrust_a > thrust_b Is thrust_a strictly greater than thrust_b?
radius <=0 Is radius negative or zero?nb_attempts<= 3 Is the number of attempts less than or equal to 3?
3 >= nb_attempts Is 3 greater than or equal to the number of attempts?
value ~= 2 Is value not equal to 2?
Relational Operators, cont.
• ***COMPARISON*** ==y == 5 % “Does y hold the value 5?”
% “Is y equal to 5?”• Example:menuChosen == 1 % did user choose menu #1 ?
8
Relational Operators, cont.
• ***COMPARISON*** ==y == 5 % “Does y hold the value 5?”
% “Is y equal to 5?”• Example:menuChosen == 1 % did user choose menu #1 ?
• Assignment = % A numerical operatory = 5; % “Store the value 5 in the
% variable y”9
Note that == and = are DIFFERENT!
Spaces or not?
• When one relational operator is made up of 2 symbols (<=, >=, ~=, ==): KEEP THEM GLUED TOGETHER
10
Spaces or not?
• When one relational operator is made up of 2 symbols (<=, >=, ~=, ==): KEEP THEM GLUED TOGETHER
• Regardless of which operator is used, a space can be used before and/or after. All these are identical to MATLAB:– thrustA<=thrustB %no spaces anywhere– thrustA <=thrustB %1 space before the operator– thrustA<= thrustB %1 space after the operator– thrustA <= thrustB %1 space before AND after
11
Scalars versus Vectors
• MOST of the time, you'll want to use relational operators with scalar values, but you can use them with vectors (and matrices).
• Operations follow similar rules to math on vectors, except everything is “element-by-element”
• Example:
Any and All
• Two functions may be helpful:any () True if ANY of the items in the vector are trueall() True if ALL of the items in the vector are true
4. Boolean Operators
• These operators take logical scalar values and perform some operation on them to yield a logical value
• Two Boolean operators allow to COMBINE relational expressions&& Logical AND|| Logical OR
• One Boolean operator allows to NEGATE the result~ Logical NOT“Negates”: turns true values into false, and false values into true
14
Boolean Operator #1: && “logical and”
• Two & symbols (“Ampersand”), glued together&&
• Both relational expressions must be true for the combined expression to be true
• X && Y yields true if and only if both X and Y are truee.g. (3 < 5) && (8 >= 8) ?(x < 1) && (x > 5) ?
x = 52.1;(5.5 < x) && (x < 100.2) ?
15
&&, continued
• Use of parenthesise.g.
(3<5) && (8>=8) true same as 3<5 && 8>=8 true
(x<3) && (x>5) falsesame as x<3 && x>5 false
16
For sanity, at least use spaces before/after the operator!
True/False
(2 > 3) && (3 < 29.3)A. True B. False C. Impossible to determine
(22 > 3) && (3 > 29.3)
D. True E. FalseF. Impossible to determine
(22 > x) && (x > 29.3)A. TrueB. False C. Impossible to determine
(x<2) && (y>0)D. True E. False F. Impossible to determine
17
• What is the result of the following statement?
True/False
F && TA. True B. False
T && FC. True D. False
F && FA. True B. False
T && TC. True D. False
18
• In other words, there are 4 options:
Boolean Operator #2: || “logical or”
• Two | (“pipe”) symbols, glued together||
• At least ONE relational expressions must be true for the combined expression to be true
• X || Y yields true if either X or Y (or both) are true
e.g. (3<5) || (5>=8) ?
x = 4.2;(x< 3) || (x > 5) ?
19
True/False
(2 > 3) || (3 < 29.3)A. True B. False C. Impossible to determine
(22 > 3) || (3 > 29.3)
D. True E. False F. Impossible to determine
(22 > x) || (x > 29.3)A. True B. False C. Impossible to determine
(x<2) || (y>0)D. True E. False F. Impossible to determine
20
• What is the result of the following statement?
True/False
F || TA. True B. False
T || FC. True D. False
F || FA. True B. False
T || TC. True D. False
21
• Again, there are 4 options:
Priorities between Boolean Operators
• Which operator has priority in the following?1 + 1 + 0 * 1
• Just like * has priority over + , && has priority over ||
– What is the result of this statement?x = 44.5;y = 55; (x<=50) || (0<y) && (y<40) ? ((x<=50) || (0<y)) && (y<40) ? (x<=50) || ((0<y) && (y<40)) ?
22
Boolean Operator #3: NOT
• One ~ symbol (“tilde”)
• “NOT” : negates a value• Example:
x = true; %keyword is known to MATLABy = ~x; %y now has the value false
• Example: The value y entered by the user should NOT be between 4 and 9 cm, inclusive:% Suppose the user enters 7.4 as a value for y~(4<=y && y<=9) ?
23
5. Operators: Result values
Type Operand type Result type
Arithmetic: Numbers Numberse.g. 5 * 3 15
Relational: Numbers Logicale.g. 5 < 3 false
Boolean: Logical Logicale.g. ~true false
true & false
24
25
Order of Operations
Operator Priority
Parenthesis () Highest
Exponentiation ^
Unary: -, NOT ~
Multiplication/division: * / \
Addition/subtraction: + -
Relational: <, <=, >, >=, ==, ~=
AND: &&
OR: ||
Assignment: = Lowest
Key Ideas
• Vocabulary: operators, operands, arithmetic, relational, boolean, unary, binary, numerical, logical
• Assignment vs. “is equal to” operator• Find the &, |, and ~ symbols on the keyboard• When does a && b && c evaluate to True?• When does a || b || c evaluate to True?• When does a && b || c && d evaluate to True?• Order of operations is respected when MATLAB executes any
expression
26
27
Conditionals
1. General Concept2. Skipping Lines of code3. The if statement4. Examples
28
Raising the Bar
• Up until now, every line of code would run sequentially.• All of programming comes down to only 3 things.
– Sequential Statements (EVERYTHING we have done so far)– Decision (Conditional) Structures (today)– Looping Structures (Thursday)
• The learning curve is really going to increase now.– Show up!– Submit something!– Ask for help!
1. General Concept of Conditionals
“CHOOSING” – This week• You may want to execute some part of code under certain
circumstances only• You may want to skip some part of a code
“LOOPING” – Starting Thursday• You may want to repeat a section of code until a new
circumstance happens• You may want to repeat a section of code for a certain
number of times
29
General Concept, cont.
• All conditional and loop syntax use BOOLEAN LOGIC to decide whether to skip/loop specific code-block.
• Review– Values: true, false– Relational operators: <, <=, >, >=, ==, ~=– Logical (Boolean) operators: &&, ||, ~
30
31
Example 1 Quadratic Equation
• Problem: Solve the Quadratic Equation
ax2 + bx + c = 0
• Theory:– Discriminant: D = b2-4ac– If D = 0, x1=x2=-b/2a
– If D > 0, x1= -b+sqrt(D)/2a, x2= -b-sqrt(D)/2a– If D < 0, no real roots
How can MATLAB only run one of those options?
32
2. Skipping lines of code
if switch
• TWO constructs can skip lines in MATLAB:
33
3. if statement
if / elseif / elseExecute statements if condition is true
Syntaxif expression statementselseif expression statementselse statementsend
ONLY these lines are necessary.
The others are optional if the problem requires them.
3. if statement
if <logical expression 1><code block 1>
elseif <logical expression 2><code block 2>
.
.
.elseif <logical expression n>
<code block n>else
<default code block>end
34
MATLAB uses the
keywords to know
where/what to skip.
If placed in the wrong spot, MATLAB skips to the wrong spot.
35
3. if statement
• Common misconception:– MATLAB skips to the “end of the code” - ABSOLUTELY NOT!– MATLAB skips to the “end” keyword and continues executing
the code (if any!)- ABSOLUTELY
36
Good Practice
• It's a common mistake to forget the end statement.
• It's a good practice to write the if (or switch or for or while) statement, then write the end statement, THEN write the contents that go inside the control structure.
Example1: weekend? weekday?
clcclear
% ask user for dayday = input('What day number is it (1-7)? ');
% find which type of day it isif day == 7 %saturdaystate = 'weekend';
elseif day == 1 %sundaystate = 'weekend';
else %any other daystate = 'weekday';
end
fprintf('That day is a %s\n', state);
37
Notice else does not have a condition. It is the default!
As far as MATLAB's concerned, day wasn't a 1 or a 7, so the else statement(s) need to run.
MATLAB goes in order: top to bottom
Improve it..
• Using the OR idea, simplify this if/elseif/else to a simple if/else.
% ask user for dayday = input('What day number is it (1-7)? ');
% find which day it isif day == 7 %saturdaystate = 'weekend';
elseif day == 1 %sundaystate = 'weekend';
else %any other daystate = 'weekday';
end
fprintf('That day is a %s\n', state);
38
When the same code appears under two different if conditions:"something's wrong".
Using Logical OR
% ask user for dayday = input('What day number is it (1-7)? ');
% find which day it isif day == 7 || day == 1 %Saturday or Sunday
state = 'weekend';else %any other day
state = 'weekday';end
fprintf('That day is a %s\n', state);
39
% find which day it isif day == 7 || 1 %Saturday or Sunday
state = 'weekend';else %any other day
state = 'weekday';end
DO NOT TRY TO SHORTCUT
Example2: Grade Letter
%choose letter gradeif grade >=90
letter = 'A';elseif grade >=80
letter = 'B';elseif grade >=70
letter = 'C';elseif grade >=60
letter = 'D';else
letter = 'FAIL';end
40
Value of grade Letter grade
90≤ grade A
80≤ grade < 90 B
70≤ grade <80 C
60≤ grade < 70 D
grade < 60 Fail
41
Example2: Grade Letter
• There is an order
%choose letter gradeif grade >=90
letter = 'A';elseif grade >=80
letter = 'B';elseif grade >=70
letter = 'C';elseif grade >=60
letter = 'D';else
letter = 'FAIL';end
90807060
42
Example2: Grade Letter
• There is an order
%choose letter gradeif grade >=90
letter = 'A';elseif grade >=80
letter = 'B';elseif grade >=70
letter = 'C';elseif grade >=60
letter = 'D';else
letter = 'FAIL';end
90807060
else means that the above condition was not true.
Hence it eliminates the 90 and above.
43
Example2: Grade Letter
• There is an order
%choose letter gradeif grade >=90
letter = 'A';elseif grade >=80
letter = 'B';elseif grade >=70
letter = 'C';elseif grade >=60
letter = 'D';else
letter = 'FAIL';end
90807060
44
Example2: Grade Letter
• There is an order
%choose letter gradeif grade >=90
letter = 'A';elseif grade >=80
letter = 'B';elseif grade >=70
letter = 'C';elseif grade >=60
letter = 'D';else
letter = 'FAIL';end
90807060
else means that the above conditionS were false.
Hence it eliminates the 80 and above.
And so on…
45
if statements within each other?
• It is absolutely possible to put a new if statement within another.
• Just remember, EACH if statement needs the end keyword that finishes it.
• This is referred as NESTED statements. (We'll talk a little more about these on Thursday).
46
Indentation is important
• It is part of the conventions of programming– “The body of an if, an elseif, or an else is indented”.– “programmers indent to better convey the structure of their programs
to human readers.” (Wikipedia: http://en.wikipedia.org/wiki/Indent_style )– Some languages (Python being the most well known) REQUIRE you to
have proper indentation• It also makes the code easy to read and “skip”• In MATLAB, using the following will Auto-Indent!
– It works if ALL your keywords if/end are present.
47
Key Ideas
• Conditionals in programming allow to SKIP (or not skip) lines of code.
• They allow the programmer to control the flow. – MATLAB's goal is to go from the 1st line to the last line.
• if statements: if and end are mandatoryelseif if there are more conditions to check after the 1st oneselse the last keyword: “for EVERYTHING else”
Keyword Number Required
if Exactly 1
elseif 0 or more (up to infinity)
else 0 or 1 (None or One)
end Exactly 1
48
STOP!
• Some errors, MATLAB will catch.
• MOST OF THESE, however, MATLAB will not. It will apply basic logic of true/false, and proceed.
The operations MATLAB performs will NOT be the ones they appear to be.
SHORTCUTS never work
%if months are jan,mar,may,jul,aug,oct,decif month==1 || 3 || 5 || 7 || 8 || 10 || 12
nb_days = 31;elseif month == 2 %February
nb_days = 29; % for leap years…else %every other months
nb_days = 30;end
49
DOES NOT WORK
AS EXPECTED
Instead, rewrite each condition separately!if month==1 || month==3 || month==5 || …
month==7 || month==8 || month==10 || month==12 nb_days = 31;…
Same applies for the && symbols…
SHORTCUTS never work
%if angle is between 0 and 90 degreesif 0<=angle<90
quadrant = 1;elseif 90<angle<=180 %quadrant 2
quadrant = 2;end
50
DOES NOT WORK
AS EXPECTED
Instead, rewrite each condition separately!
if 0<=angle && angle<90quadrant = 1;
elseif 90<angle && angle<=180quadrant = 2;
end
And / Or Mixups
51
It's not technically an “if” problem, but
if month==1 || month==3 || month==5 || …month==7 || month==8 || month==10 || month==12
nb_days = 31;
is MUCH different than
if month==1 && month==3 && month==5 && …month==7 && month==8 && month==10 && month==12
nb_days = 31;
Which month number is equal to both 1 and 3 and 5 and …?
52
Horrible habits
• The following won't make the code “crash” or “work wrong”.
They're just really bad habits!
Find the 3 issues
• Common programmer issues%ask user for his/her gradegrade = input('Enter your grade (0-100): ');
%choose letter gradeif grade >=90;
letter = 'A';elseif grade >=80 && grade<=90
letter = 'B';elseif grade >=70 && grade<=80
letter = 'C';elseif grade >=60 && grade<=70
letter = 'D';else grade<=60
letter = 'FAIL';end
53
Issue 1: that semicolon
• Common programmer issues%ask user for his/her gradegrade = input('Enter your grade (0-100): ');
%choose letter gradeif grade >=90;
letter = 'A';elseif grade >=80 && grade<=90
letter = 'B';elseif grade >=70 && grade<=80
letter = 'C';elseif grade >=60 && grade<=70
letter = 'D';else grade<=60
letter = 'FAIL';end
54
No semicolon. There is no output to suppress on this line, AND it's not the end of the if statement.
Issue 2: overdoing it
• Common programmer issues%ask user for his/her gradegrade = input('Enter your grade (0-100): ');
%choose letter gradeif grade >=90;
letter = 'A';elseif grade >=80 && grade<=90
letter = 'B';elseif grade >=70 && grade<=80
letter = 'C';elseif grade >=60 && grade<=70
letter = 'D';else grade<=60
letter = 'FAIL';end
55
REDUNDANT conditions
You're asking MATLAB to RE-CHECK a condition MATLAB already knows to be TRUE….
Issue 3: ERROR!Leave the else alone!
• Common programmer issues%ask user for his/her gradegrade = input('Enter your grade (0-100): ');
%choose letter gradeif grade >=90;
letter = 'A';elseif grade >=80 && grade<=90
letter = 'B';elseif grade >=70 && grade<=80
letter = 'C';elseif grade >=60 && grade<=70
letter = 'D';else grade<=60
letter = 'FAIL';end
56
No condition on the ELSE clause – only on IF and ELSEIF.The last else is for “EVERYTHING” else.
Write a section of code that will assign the number of days in a given month to a variable
Thirty days hath September,April, June, and November.All the rest have thirty-one,Excepting February alone,And that has twenty-eight days clear,And twenty-nine in each leap year
if-elseif-else Review
57
Write a section of code that will assign the number of days in a given month to a variable
MATLAB code:
if-elseif-else Review
%Request user to enter the month number (Jan=1, Aug=8)month = input('Enter the month number: ');
% If month is Jan, Mar, May, Jul, Aug, Oct, Decif month==1 || month==3 || month==5 || month==7 || …
month==8 || month==10 || month==12nb_days = 31;
elseif month == 2 % Februarynb_days = 29; % for leap years…
else % every other monthnb_days = 30;
end 58
%if months are jan,mar,may,jul,aug,oct,decif month==1 || month==3 || month==5 || month==7 || …
month==8 || month==10 || month==12nb_days = 31;
elseif month == 2 %Februarynb_days = 29; % for leap years…
else %every other monthsnb_days = 30;
end
What are some characteristics of this code segment?
What are its limitations?
if-elseif-else Review
59
60
switch statement
• Allows for evaluation of multiple cases of the same variable
• The switch statement is looking for the variable to have an exact match to one of the cases. (No a<x && x<=b)
• Specification may have multiple values enclosed in braces {…}
• The default case catches any values of the parameter other than the specified cases.
• The default case should trap bad parameter values.
General Template
switch variablecase specification 1
<code block 1>....case specification n
<code block n>otherwise
<default block>end
61
if <condition 1>
<code block 1>
elseif <condition 2> <code block 2>..elseif <condition n> <code block n>else <default block>end
There is no limit to the number of cases.
switch Example 1: Multiple Cases
Instead we use…switch month
case {1,3,5,7,8,10,12} % 31-day monthsdays = 31;case 2days = 29; % leap year to be coded..case {4,6,9,11} % 30-day monthsdays = 30; otherwisefprintf('Invalid Entry.\n');
end
62
Let us modify the calendar example from an if to a switch
if month==1 || month== 3 || month== 5 || …month== 7 || month== 8 || month== 10 || month== 12
Big advantage: reduces long OR statements of equality
63
Simulated “Run”
% Suppose month is 4
switch monthcase {1,3,5,7,8,10,12} % 31-days months
days = 31;case 2
days = 29; % leap year to be coded..case {4,6,9,11} % 30-days months
days = 30; otherwise
fprintf('Invalid Entry.\n');end
Simulated “Run”
% Suppose month is 4
switch monthcase {1,3,5,7,8,10,12} % 31-days months
days = 31;case 2
days = 29; % leap year to be coded..case {4,6,9,11} % 30-days months
days = 30; otherwise
fprintf('Invalid Entry.\n');end
64
Simulated “Run”
% Suppose month is 4
switch monthcase {1,3,5,7,8,10,12} % 31-days months
days = 31;case 2
days = 29; % leap year to be coded..case {4,6,9,11} % 30-days months
days = 30; otherwise
fprintf('Invalid Entry.\n');end
65
Simulated “Run”
% Suppose month is 4
switch monthcase {1,3,5,7,8,10,12} % 31-days months
days = 31;case 2
days = 29; % leap year to be coded..case {4,6,9,11} %30-days months
days = 30; otherwise
fprintf('Invalid Entry.\n');end
66
Simulated “Run”
% Suppose month is 4
switch monthcase {1,3,5,7,8,10,12} % 31-days months
days = 31;case 2
days = 29; % leap year to be coded..case {4,6,9,11} % 30-days months
days = 30; otherwise
fprintf('Invalid Entry.\n');end
67
Simulated “Run”
% Suppose month is 4
switch monthcase {1,3,5,7,8,10,12} % 31-days months
days = 31;case 2
days = 29; % leap year to be coded..case {4,6,9,11} % 30-days months
days = 30; otherwise
fprintf('Invalid Entry.\n');end
68
Simulated “Run”
% Suppose month is 4
switch monthcase {1,3,5,7,8,10,12} % 31-days months
days = 31;case 2
days = 29; % leap year to be coded..case {4,6,9,11} % 30-days months
days = 30; otherwise
fprintf('Invalid Entry.\n');end
6969
Simulated “Run”
% Suppose month is 4
switch monthcase {1,3,5,7,8,10,12} % 31-days months
days = 31;case 2
days = 29; % leap year to be coded..case {4,6,9,11} % 30-days months
days = 30; otherwise
fprintf('Invalid Entry.\n');end
………
7070
switch Example 2: strings
71
switch statements can also be used to evaluate stringsmonth = input('Enter the month: ', 's')
switch monthcase {'Jan','March','May','July'... } %31-days -days = 31;case 'Feb'
days = 29; %leap year to be coded..case {'April', 'June','Sept','Nov'} %30-days
days = 30; otherwise
fprintf('Invalid Entry.\n');end
switch - Menu's
• Several programs request the user to select an item from a menu:
72
switch Example 3: Menu Options
%ask user what he'd like to domenu_choice = input('Select Item 1 to 4: ');
%direct code to proper actionswitch menu_choice
case 1fprintf('You have selected 1.\n')
case 2fprintf('You have selected a number 2.\n')
case 3fprintf('You have selected a number 3.\n')
case 4fprintf('You have selected a number 4.\n')
otherwisefprintf('Invalid Entry.\n');
end
73
if versus switch
• As general ideas:
74
if switch
Combination of || statements that check equalityExample:
x==1 || x==2 || x==3 || x==4 Yes √ preferred
Inequalities (<, <=, >=, >) Yes Impossible
Conditions with &&: x == 2 && x == 7 Yes Impossible
Conditions that check multiple variablesSuch as: x==4 && y==7 √ preferred Impossible
Menus ok… √ preferred