Operators i e symbols
This presentation is the property of its rightful owner.
Sponsored Links
1 / 74

“Operators” (i.e. “symbols”) PowerPoint PPT Presentation


  • 85 Views
  • Uploaded on
  • Presentation posted in: General

“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.

Download Presentation

“Operators” (i.e. “symbols”)

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Operators i e symbols

“Operators” (i.e. “symbols”)

Overview: Specific Symbols that Represent Specific Actions

Arithmetic

Relational

Boolean

Output values


Overview most operators

Overview: most Operators

  • There are 3 primary groups of operators

    One programming operator is very different from its use in math:


Overview cont

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 cont1

Overview, cont.

  • There are 2 types of operands:

    • Numerical1, 3.5, -47

    • Logicaltrue, 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 cont2

Overview, cont.

  • There are 2 types of operands:

    • Numerical 1, 3.5, -47

    • Logicaltrue, 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, and 0?!

True

False

1

0


3 relational operators

3. Relational Operators

  • Relational operators allow a comparison to be evaluated.

    Is thrust_a greater than thrust_b?  True / FalseIs surface1 equal to surface2?  True / False?Isload1less than or equal toload2?  True / False?

  • Examples:


Relational operators cont

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 cont1

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

Spaces or not?

  • When one relational operator is made up of 2 symbols (<=, >=, ~=, ==): KEEP THEM GLUED TOGETHER


Spaces or not1

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

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

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

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

Boolean Operator #1: && “logical and”

  • Two & symbols (“Ampersand”), glued together

    &&

  • Both relational expressions must be truefor the combined expression to be true

  • X && Yyields 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

&&, continued

  • Use of parenthesis

    e.g.

    (3<5) && (8>=8)true

    same as 3<5 && 8>=8true

    (x<3) && (x>5)false

    same as x<3 && x>5false

For sanity, at least use spaces before/after the operator!


True false

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 false1

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

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 || Yyields true if eitherXorY (or both) are true

    e.g.(3<5) || (5>=8)?

    x = 4.2;

    (x< 3) || (x > 5)?


True false2

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 false3

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 b oolean operators

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

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

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


Order of operations

Order of Operations


Key ideas

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

Conditionals

General Concept

Skipping Lines of code

The if statement

Examples


Raising the bar

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

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

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

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

2. Skipping lines of code

  • TWO constructs can skip linesin MATLAB:

if

switch


3 if statement

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 statement1

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 statement2

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

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

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

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

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

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 letter1

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 letter2

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 letter3

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 letter4

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

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

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 ideas1

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

    elseifif there are more conditions to check after the 1st ones

    elsethe last keyword: “for EVERYTHING else”


Operators i e symbols

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

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 work1

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


And or mixups

And / Or Mixups

It's not technically an “if” problem, but

ifmonth==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 …?


Horrible habits

Horrible habits

  • The following won't make the code “crash” or “work wrong”.

    They're just really bad habits!


Find the 3 issues

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


Issue 1 that semicolon

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

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

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

REDUNDANT conditions

You're asking MATLAB to RE-CHECK a condition MATLAB already knows to be TRUE….


Issue 3 error leave the else alone

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

No condition on the ELSE clause – only on IF and ELSEIF.

The last elseis for “EVERYTHING” else.


If elseif else review

if-elseif-else Review

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 review1

if-elseif-else Review

Write a section of code that will assign the number of days in a given month to a variable

MATLAB code:

%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


If elseif else review2

if-elseif-else Review

%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?


Switch statement

switchstatement

  • Allows for evaluation of multiple cases of the samevariable

  • The switch statement is looking for the variable to have an exact matchto 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

General Template

switchvariable

casespecification 1

<code block 1>

.

.

.

.

casespecification n

<code block n>

otherwise

<default block>

end

if <condition 1>

<code block 1>

elseif<condition 2>

<code block 2>

.

.

elseif<condition n>

<code block n>

There is no limit to the number of cases.

else

<default block>

end


Switch example 1 multiple cases

switch Example 1: Multiple Cases

  • Let us modify the calendar example from an if to a switch

  • ifmonth==1 || month== 3 || month== 5 || …

  • month== 7 || month== 8 || month== 10 || month== 12

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

Big advantage: reduces long OR statements of equality


Simulated run

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


Simulated run1

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


Simulated run2

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


Simulated run3

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


Simulated run4

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


Simulated run5

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


Simulated run6

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

69


Simulated run7

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

………

70


Switch example 2 strings

switch Example 2: strings

  • 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


Switch menu s

switch - Menu's

  • Several programs request the user to select an item from a menu:


Switch example 3 menu options

switchExample 3: Menu Options

%ask user what he'd like to do

menu_choice = input('Select Item 1 to 4: ');

%direct code to proper action

switchmenu_choice

case1

fprintf('You have selected 1.\n')

case2

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


If versus switch

ifversus switch

  • As general ideas:


  • Login