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

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

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

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

Overview: Specific Symbols that Represent Specific Actions

Arithmetic

Relational

Boolean

Output values

- There are 3 primary groups of operators
One programming operator is very different from its use in math:

- 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

- 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”

- 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

0

- 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:

- ***COMPARISON***==
y == 5% “Does y hold the value 5?”

% “Is y equal to 5?”

- Example:
menuChosen == 1 % did user choose menu #1 ?

- ***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!

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

- 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

- 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:

- 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

- 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

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

- 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!

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

F && T

- True
- False
T && F

- True
- False

F && F

- True
- False
T && T

- True
- False

- In other words, there are 4 options:

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

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

F || T

- True
- False
T || F

- True
- False

F || F

- True
- False
T || T

- True
- False

- Again, there are 4 options:

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

- What is the result of this statement?

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

TypeOperand typeResult type

Arithmetic: Numbers Numbers

e.g.5 * 315

Relational:NumbersLogical

e.g.5 < 3false

Boolean:LogicalLogical

e.g.~truefalse

true & false

- 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

- 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!

“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

- 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:&&, ||, ~

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?

- TWO constructs can skip linesin MATLAB:

if

switch

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.

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.

- 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

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

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.

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

% 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

%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

- 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

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

- 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

- 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…

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

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

- 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”

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

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

%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

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

- The following won't make the code “crash” or “work wrong”.
They're just really bad habits!

- 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

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

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

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

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

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

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

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

- 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

% 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

% 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

% 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

% 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

% 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

% 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

% 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

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

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

%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

- As general ideas: