740 likes | 950 Views
“Operators” (i.e. “symbols”). Overview: Specific Symbols that Represent Specific Actions Arithmetic Relational Boolean Output values. Overview: most Operators. There are 3 primary groups of operators One programming operator is very different from its use in math: . Overview, cont.
E N D
“Operators” (i.e. “symbols”) Overview: Specific Symbols that Represent Specific Actions Arithmetic Relational Boolean Output values
Overview: most Operators • There are 3 primary groups of operators One programming operator is very different from its use in math:
Overview, cont. • Operators work on operands. Binary Operator Requires two operands to work 4 * 5 operands Multiplication operator -5 Unary Operator Requires one operand to work operand Negative operator
Overview, cont. • There are 2 types of operands: • Numerical 1, 3.5, -47 • Logical true, false Arithmetic(+, -, /, *, ^, =) and relational(<, <=, >, >= ,==, ~=) operators work with numerical operands Numerical Operands kineticEnergy = 1 / 2 * mass * vel^ 2 Arithmetic operators Assign operator: “place one or more values into memory”
Overview, cont. • There are 2 types of operands: • Numerical 1, 3.5, -47 • Logical true, false • Boolean (&&,||,~) operators work on logical operands “ if this is true and this is false… do something” if (it's raining outside) and (you have an umbrella) go, you won't get wet else stay inside! end
True, False, 1, and 0?! True False 1 0
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?Isload1less than or equal toload2? True / False? • Examples:
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 ?
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” Notethat == and = are DIFFERENT!
Spaces or not? • When one relational operator is made up of 2 symbols (<=, >=, ~=, ==): KEEP THEM GLUED TOGETHER
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
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 true all()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 ||LogicalOR • One Boolean operator allows to NEGATE the result ~ Logical NOT “Negates”: turns true values into false, and false values into true
Boolean Operator #1: && “logical and” • Two & symbols (“Ampersand”), glued together && • Both relational expressions must be truefor the combined expression to be true • X && Y yields true if and only if both XandY are true e.g. (3 < 5) && (8 >= 8) ? (x < 1) && (x > 5) ? x = 52.1; (5.5 < x) && (x < 100.2) ?
&&, continued • Use of parenthesis e.g. (3<5) && (8>=8) true same as 3<5 && 8>=8 true (x<3) && (x>5) false same as x<3 && x>5 false For sanity, at least use spaces before/after the operator!
True/False (2 > 3) && (3 < 29.3) • True • False • Impossible to determine (22 > 3) && (3 > 29.3) • True • False • Impossible to determine (22 > x) && (x > 29.3) • True • False • Impossible to determine (x<2) && (y>0) • True • False • Impossible to determine • What is the result of the following statement?
True/False F && T • True • False T && F • True • False F && F • True • False T && T • True • False • In other words, there are 4 options:
Boolean Operator #2: || “logical or” • Two |(“pipe”) symbols, glued together || • At least ONE relational expressions must be truefor the combined expression to be true • X || Y yields true if eitherXorY (or both) are true e.g. (3<5) || (5>=8) ? x = 4.2; (x< 3) || (x > 5) ?
True/False (2 > 3) || (3 < 29.3) • True • False • Impossible to determine (22 > 3) || (3 > 29.3) • True • False • Impossible to determine (22 > x) || (x > 29.3) • True • False • Impossible to determine (x<2) || (y>0) • True • False • Impossible to determine • What is the result of the following statement?
True/False F || T • True • False T || F • True • False F || F • True • False T || T • True • False • 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)) ?
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 fory ~(4<=y && y<=9) ?
5. Operators: Result values Type Operand type Result type Arithmetic: Numbers Numbers e.g. 5 * 315 Relational: Numbers Logical e.g. 5 < 3false Boolean: Logical Logical e.g. ~truefalse true & false
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
Conditionals General Concept Skipping Lines of code The if statement Examples
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
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: &&, ||, ~
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?
2. Skipping lines of code • TWO constructs can skip linesin MATLAB: if switch
3. if statement if / elseif / else Execute statements if condition is true Syntax ifexpression statements elseifexpression statements else statements end 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 MATLAB uses the keywords to know where/what to skip. If placed in the wrong spot, MATLAB skips to the wrong spot.
3. if statement • Common misconception: • MATLAB skips to the “end of the code” - ABSOLUTELY NOT! • MATLAB skips to the “end” keywordand continues executing the code (if any!)- ABSOLUTELY
Good Practice • It's a common mistake to forget the end statement. • It's a good practice to write the if (or switchor for or while) statement, then write the end statement, THEN write the contents that go inside the control structure.
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); MATLAB goes in order: top to bottom Notice elsedoes not have a condition. It is the default! As far as MATLAB's concerned, daywasn't a 1 or a 7, so the else statement(s) need to run.
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); When the same code appears under two different if conditions: "something's wrong".
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); % 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
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
Example2: Grade Letter • There is an order 60 70 80 90 %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
Example2: Grade Letter • There is an order 60 70 80 90 %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 else means that the above condition was not true. Hence it eliminates the 90 and above.
Example2: Grade Letter • There is an order 60 70 80 90 %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
Example2: Grade Letter • There is an order 60 70 80 90 %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 else means that the above conditionS were false. Hence it eliminates the 80 and above. And so on…
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).
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.
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 mandatory elseif if there are more conditions to check after the 1st ones else the last keyword: “for EVERYTHING else”
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,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 DOESNOTWORKAS 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 degrees if 0<=angle<90 quadrant = 1; elseif 90<angle<=180 %quadrant 2 quadrant = 2; end DOESNOTWORKAS EXPECTED • Instead, rewrite each condition separately! • if 0<=angle && angle<90 • quadrant = 1; • elseif 90<angle && angle<=180 • quadrant = 2; • end