“Operators” (i.e. “symbols”)
description
Transcript of “Operators” (i.e. “symbols”)
![Page 1: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/1.jpg)
1
“Operators” (i.e. “symbols”)
1. Overview: Specific Symbols that Represent Specific Actions2. Arithmetic3. Relational4. Boolean5. Output values
![Page 2: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/2.jpg)
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”
![Page 3: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/3.jpg)
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
![Page 4: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/4.jpg)
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
![Page 5: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/5.jpg)
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
![Page 6: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/6.jpg)
True, False, 1, and 0?!
TrueFalse
10
![Page 7: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/7.jpg)
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?
![Page 8: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/8.jpg)
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
![Page 9: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/9.jpg)
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!
![Page 10: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/10.jpg)
Spaces or not?
• When one relational operator is made up of 2 symbols (<=, >=, ~=, ==): KEEP THEM GLUED TOGETHER
10
![Page 11: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/11.jpg)
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
![Page 12: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/12.jpg)
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:
![Page 13: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/13.jpg)
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
![Page 14: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/14.jpg)
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
![Page 15: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/15.jpg)
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
![Page 16: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/16.jpg)
&&, 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!
![Page 17: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/17.jpg)
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?
![Page 18: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/18.jpg)
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:
![Page 19: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/19.jpg)
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
![Page 20: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/20.jpg)
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?
![Page 21: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/21.jpg)
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:
![Page 22: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/22.jpg)
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
![Page 23: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/23.jpg)
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
![Page 24: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/24.jpg)
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
![Page 25: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/25.jpg)
25
Order of Operations
Operator Priority
Parenthesis () Highest
Exponentiation ^
Unary: -, NOT ~
Multiplication/division: * / \
Addition/subtraction: + -
Relational: <, <=, >, >=, ==, ~=
AND: &&
OR: ||
Assignment: = Lowest
![Page 26: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/26.jpg)
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
![Page 27: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/27.jpg)
27
Conditionals
1. General Concept2. Skipping Lines of code3. The if statement4. Examples
![Page 28: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/28.jpg)
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!
![Page 29: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/29.jpg)
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
![Page 30: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/30.jpg)
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
![Page 31: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/31.jpg)
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?
![Page 32: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/32.jpg)
32
2. Skipping lines of code
if switch
• TWO constructs can skip lines in MATLAB:
![Page 33: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/33.jpg)
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.
![Page 34: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/34.jpg)
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.
![Page 35: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/35.jpg)
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
![Page 36: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/36.jpg)
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.
![Page 37: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/37.jpg)
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
![Page 38: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/38.jpg)
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".
![Page 39: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/39.jpg)
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
![Page 40: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/40.jpg)
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
![Page 41: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/41.jpg)
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
![Page 42: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/42.jpg)
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.
![Page 43: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/43.jpg)
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
![Page 44: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/44.jpg)
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…
![Page 45: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/45.jpg)
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).
![Page 46: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/46.jpg)
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.
![Page 47: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/47.jpg)
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
![Page 48: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/48.jpg)
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.
![Page 49: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/49.jpg)
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…
![Page 50: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/50.jpg)
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
![Page 51: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/51.jpg)
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 …?
![Page 52: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/52.jpg)
52
Horrible habits
• The following won't make the code “crash” or “work wrong”.
They're just really bad habits!
![Page 53: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/53.jpg)
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
![Page 54: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/54.jpg)
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.
![Page 55: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/55.jpg)
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….
![Page 56: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/56.jpg)
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.
![Page 57: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/57.jpg)
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
![Page 58: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/58.jpg)
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
![Page 59: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/59.jpg)
%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
![Page 60: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/60.jpg)
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.
![Page 61: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/61.jpg)
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.
![Page 62: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/62.jpg)
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
![Page 63: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/63.jpg)
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
![Page 64: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/64.jpg)
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
![Page 65: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/65.jpg)
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
![Page 66: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/66.jpg)
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
![Page 67: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/67.jpg)
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
![Page 68: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/68.jpg)
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
![Page 69: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/69.jpg)
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
![Page 70: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/70.jpg)
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
![Page 71: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/71.jpg)
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
![Page 72: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/72.jpg)
switch - Menu's
• Several programs request the user to select an item from a menu:
72
![Page 73: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/73.jpg)
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
![Page 74: “Operators” (i.e. “symbols”)](https://reader035.fdocuments.in/reader035/viewer/2022062410/568160bc550346895dcfe052/html5/thumbnails/74.jpg)
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