Download presentation
Presentation is loading. Please wait.
Published byMadeline Cole Modified over 9 years ago
1
“Operators” (i.e. “symbols”) 1.Overview: Specific Symbols that Represent Specific Actions 2.Arithmetic 3.Relational 4.Boolean 5.Output values 1
2
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”
3
Overview, cont. Operators work on operands. 3 4 * 5 operands Multiplication operator -5 operand Negative operator Binary Operator Requires two operands to work Unary Operator Requires one operand to work
4
Overview, cont. There are 2 types of operands: 1.Numerical 1, 3.5, -47 2.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
5
Overview, cont. There are 2 types of operands: 1.Numerical 1, 3.5, -47 2.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 else stay inside! end
6
True, False, 1, and 0?! True False 1 0
7
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?
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 ? 8
9
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 operator y = 5;% “Store the value 5 in the % variable y” 9 Note that == and = are DIFFERENT!
10
Spaces or not? When one relational operator is made up of 2 symbols ( =, ~=, == ): KEEP THEM GLUED TOGETHER 10
11
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
12
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 12
13
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 true e.g.(3 = 8)? (x 5)? x = 52.1; (5.5 < x) && (x < 100.2) ? 13
14
&&, continued Use of parenthesis e.g. (3 =8)true same as 3 =8true (x 5)false same as x 5false 14 For sanity, at least use spaces before/after the operator!
15
True/False (2 > 3) && (3 < 29.3) A.True B.False C.Impossible to determine (22 > 3) && (3 > 29.3) A.True B.False C.Impossible to determine (22 > x) && (x > 29.3) A.True B.False C.Impossible to determine (x 0) A.True B.False C.Impossible to determine 15 What is the result of the following statement?
16
True/False F && T A.True B.False T && F A.True B.False F && F A.True B.False T && T A.True B.False 16 In other words, there are 4 options:
17
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 =8)? x = 4.2; (x 5)? 17
18
True/False (2 > 3) || (3 < 29.3) A.True B.False C.Impossible to determine (22 > 3) || (3 > 29.3) A.True B.False C.Impossible to determine (22 > x) || (x > 29.3) A.True B.False C.Impossible to determine (x 0) A.True B.False C.Impossible to determine 18 What is the result of the following statement?
19
True/False F || T A.True B.False T || F A.True B.False F || F A.True B.False T || T A.True B.False 19 Again, there are 4 options:
20
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))? 20
21
Boolean Operator #3: NOT One ~ symbol (“tilde”) “NOT” : negates a value Example: x = true; %keyword is known to MATLAB y = ~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)? 21
22
5. Operators: Result values TypeOperand typeResult type Arithmetic: Numbers Numbers e.g. 5 * 315 Relational:NumbersLogical e.g. 5 < 3false Boolean:LogicalLogical e.g. ~truefalse true & false 22
23
Order of Operations OperatorPriority Parenthesis ()Highest Exponentiation ^ Unary: -, NOT ~ Multiplication/division: * / \ Addition/subtraction: + - Relational:, >=, ==, ~= AND: && OR: || Assignment: =Lowest 23
24
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! 24
25
1. General Concept of Conditionals “CHOOSING” – Today 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 25
26
Example 1 26 Quadratic Equation Problem: Solve the Quadratic Equation ax 2 + bx + c = 0 Theory: – Discriminant: D = b 2 -4ac – If D = 0, x 1 =x 2 =-b/2a – If D > 0, x 1 = -b+sqrt(D)/2a, x 2 = -b-sqrt(D)/2a – If D < 0, no real roots How can MATLAB only run one of those options?
27
2. Skipping lines of code ifswitch 27 TWO constructs can skip lines in MATLAB: Not being covered, but you may see it Slides at the end discuss it if you want to see it
28
3. if statement if / elseif / else Execute statements if condition is true Syntax if expression statements elseif expression statements else statements end 28 ONLY these lines are necessary. The others are optional if the problem requires them.
29
KeywordNumber Required if 1 elseif 0 - Infinity else 0 or 1 end 1 29
30
3. if statement if elseif. elseif else end 30 MATLAB uses the keywords to know where/what to skip. If placed in the wrong spot, MATLAB skips to the wrong spot.
31
Demo Time Check the discriminant! 31
32
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 32
33
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. 33
34
Example1: weekend? weekday? clc clear % ask user for day day = input('What day number is it (1-7)? '); % find which type of day it is if day == 7 %saturday state = 'weekend'; elseif day == 1 %sunday state = 'weekend'; else %any other day state = 'weekday'; end fprintf('That day is a %s\n', state); 34 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
35
Improve it.. Using the OR idea, simplify this if/elseif/else to a simple if/else. % ask user for day day = input('What day number is it (1-7)? '); % find which day it is if day == 7 %saturday state = 'weekend'; elseif day == 1 %sunday state = 'weekend'; else %any other day state = 'weekday'; end fprintf('That day is a %s\n', state); 35 When the same code appears under two different if conditions: "something's wrong".
36
Using Logical OR % ask user for day day = input('What day number is it (1-7)? '); % find which day it is if day == 7 || day == 1 %Saturday or Sunday state = 'weekend'; else %any other day state = 'weekday'; end fprintf('That day is a %s\n', state); 36 % find which day it is if day == 7 || 1 %Saturday or Sunday state = 'weekend'; else %any other day state = 'weekday'; end DO NOT TRY TO SHORTCUT
37
Example2: Grade Letter %choose letter grade if grade >=90 letter = 'A'; elseif grade >=80 letter = 'B'; elseif grade >=70 letter = 'C'; elseif grade >=60 letter = 'D'; else letter = 'FAIL'; end 37 Value of gradeLetter grade 90≤ gradeA 80≤ grade < 90B 70≤ grade <80C 60≤ grade < 70D grade < 60Fail
38
Example2: Grade Letter There is an order 38 %choose letter grade if grade >=90 letter = 'A'; elseif grade >=80 letter = 'B'; elseif grade >=70 letter = 'C'; elseif grade >=60 letter = 'D'; else letter = 'FAIL'; end 90807060
39
Example2: Grade Letter There is an order 39 %choose letter grade if 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.
40
Example2: Grade Letter There is an order 40 %choose letter grade if grade >=90 letter = 'A'; elseif grade >=80 letter = 'B'; elseif grade >=70 letter = 'C'; elseif grade >=60 letter = 'D'; else letter = 'FAIL'; end 90807060
41
Example2: Grade Letter There is an order 41 %choose letter grade if 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…
42
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 later). 42
43
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 )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. 43
44
SHORTCUTS never work %if months are jan,mar,may,jul,aug,oct,dec if 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 44 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…
45
SHORTCUTS never work %if angle is between 0 and 90 degrees if 0<=angle<90 quadrant = 1; elseif 90<angle<=180 %quadrant 2 quadrant = 2; end 45 DOES NOT WORK AS EXPECTED Instead, rewrite each condition separately! if 0<=angle && angle<90 quadrant = 1; elseif 90<angle && angle<=180 quadrant = 2; end
46
And / Or Mixups 46 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 …?
47
What is the difference? %if months are jan,mar,may,jul,aug,oct,dec if month==1 || month==3 || month==5 || … month==7 || month==8 || month==10 || month==12 nb_days = 31; elseif month == 2 %February nb_days = 29; % for leap years… else %every other months nb_days = 30; end 47 %if months are jan,mar,may,jul,aug,oct,dec if month==1 || month==3 || month==5 || … month==7 || month==8 || month==10 || month==12 nb_days = 31; else if month == 2 %February nb_days = 29; % for leap years… else %every other months nb_days = 30; end This Works This Doesn’t
48
Horrible habits The following won't make the code “crash” or “work wrong”. They're just really bad habits! 48
49
Find the 3 issues Common programmer issues %ask user for his/her grade grade = input('Enter your grade (0-100): '); %choose letter grade if 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 49
50
Issue 1: that semicolon Common programmer issues %ask user for his/her grade grade = input('Enter your grade (0-100): '); %choose letter grade if 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 50 No semicolon. There is no output to suppress on this line, AND it's not the end of the if statement.
51
Issue 2: overdoing it Common programmer issues %ask user for his/her grade grade = input('Enter your grade (0-100): '); %choose letter grade if 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 51 REDUNDANT conditions You're asking MATLAB to RE- CHECK a condition MATLAB already knows to be TRUE….
52
Issue 3: ERROR! Leave the else alone! Common programmer issues %ask user for his/her grade grade = input('Enter your grade (0-100): '); %choose letter grade if 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 52 No condition on the ELSE clause – only on IF and ELSEIF. The last else is for “EVERYTHING” else.
53
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 53
54
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, Dec if month==1 || month==3 || month==5 || month==7 || … month==8 || month==10 || month==12 nb_days = 31; elseif month == 2 % February nb_days = 29; % for leap years… else % every other month nb_days = 30; end 54
55
%if months are jan,mar,may,jul,aug,oct,dec if month==1 || month==3 || month==5 || month==7 || … month==8 || month==10 || month==12 nb_days = 31; elseif month == 2 %February nb_days = 29; % for leap years… else %every other months nb_days = 30; end What are some characteristics of this code segment? What are its limitations? if-elseif-else Review 55
56
Questions? (The switch slides that follow this are optional for those that want to understand switches, but we will not be covering them and we will not be asking required test questions regarding switches. They are still fodder for extra credit questions.) 56
57
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. 57
58
General Template switch variable case specification 1. case specification n otherwise end 58 if elseif. elseif else end There is no limit to the number of cases.
59
switch Example 1: Multiple Cases Instead we use… switch month case {1,3,5,7,8,10,12} % 31-day months days = 31; case 2 days = 29; % leap year to be coded.. case {4,6,9,11} % 30-day months days = 30; otherwise fprintf('Invalid Entry.\n'); end 59 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
60
Simulated “Run” % Suppose month is 4 switch month case {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 60
61
Simulated “Run” % Suppose month is 4 switch month case {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 61
62
Simulated “Run” % Suppose month is 4 switch month case {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 62
63
Simulated “Run” % Suppose month is 4 switch month case {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 63
64
Simulated “Run” % Suppose month is 4 switch month case {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
65
Simulated “Run” % Suppose month is 4 switch month case {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
66
Simulated “Run” % Suppose month is 4 switch month case {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
67
Simulated “Run” % Suppose month is 4 switch month case {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
68
switch Example 2: strings 68 switch statements can also be used to evaluate strings month = input('Enter the month: ', 's') switch month case {'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
69
switch - Menu's Several programs request the user to select an item from a menu: 69
70
switch Example 3: Menu Options %ask user what he'd like to do menu_choice = input('Select Item 1 to 4: '); %direct code to proper action switch menu_choice case 1 fprintf('You have selected 1.\n') case 2 fprintf('You have selected a number 2.\n') case 3 fprintf('You have selected a number 3.\n') case 4 fprintf('You have selected a number 4.\n') otherwise fprintf('Invalid Entry.\n'); end 70
71
if versus switch As general ideas: 71 ifswitch Combination of || statements that check equality Example: x==1 || x==2 || x==3 || x==4 Yes√ preferred Inequalities ( =, >)YesImpossible Conditions with &&: x == 2 && x == 7 YesImpossible Conditions that check multiple variables Such as: x==4 && y==7 √ preferredImpossible Menusok…√ preferred
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.