Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

ECE105 Day6 Branches WhileLoops

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

See last slide for

licensing details

DAY 6
RELATIONAL OPERATORS
LOGIC OPERATORS
IF/ELSE
SWITCH/CASE, TRY/CATCH
WHILE LOOPS
ECE105 – Cody Anderson
The real power of programming
 Our codes so far have been sequential: they carry out
each line in order

 The real power of programming comes from making


decisions and repeating steps
 We do this through branches and loops
 branches: decide which section of code to run
 loops: repeat sections of code

 The decisions that guide branches and loops are written


as logical statements
Logical Data Type
Relational operators
Logic operators
Data types
Array

Logical Char Numeric Cell Structure Function


Handle

Int8, 16, Uint8, 16, Single Double


32, 64 32, 64

The logical data type


 Can hold only two possible values: true (1) or false (0)

 Uses only one byte of memory (numbers use 8 bytes)

 Typically created from a relational operator (e.g. w>4)


Logical data type Every number (except 0)
becomes true when
converted to a logical

Directly defining logical values

When a logical variable is used in an


arithmetic operation, MATLAB automatically
converts to the numeric data type
 true*5 means nothing
 1*5 does mean something
Relational Operators

Operator Name
== Equal to
~= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to

Important distinction:
= assignment operator
== evaluate if two variables are equivalent
Rounding errors
 MATLAB double type is precise
to ~16 significant figures

 This introduces a small rounding


error for some numbers
 As a result, two values that are
equivalent mathematically may
not be seen as equivalent

 To avoid this, use the difference


approach shown here. It checks
if two values are nearly equal
(within a certain threshold)
Logical mask from relational operator

Original matrix

Logical mask that tells us whether


each value in A is
• > 4 (true)
• ≤ 4 (false)
Logic Operators
Operator Name Logic
& AND Output true iff all inputs are true

&& AND (for scalars)


| OR Output true if at least one input is true

|| OR (for scalars)
xor( ) Exclusive OR Output true if one and only one input is true

~ NOT Reverse the logic of a single input

*The scalar operators (&& and ||) only work for scalar inputs,
but they are more efficient
Logic Operator Examples

false false

Given these variable definitions,


compute the result of the operations
*MATLAB converts numeric data to
logical data when needed: true false
 0  false
 Any other number  true

false true true


Logic and Relational Operator Examples

true

Given these variable false


definitions, compute the
result of the operations

true

true

true
Branching statements
if/else
switch/case
try/catch
if/else statements
 At a fork, only one path gets taken
 Paths are evaluated in order, ignoring all
other paths
 If Condition #1 is true, that branch is taken
(even if a later condition is true)
 If Condition #1 is false, move on to evaluate
Condition #2
 And so on…
 Once an else statement is reached, that
branch is taken (no conditions)
 Can have any number of elseif’s
 It’s possible to never choose a branch (must
have no else statement)
if/else statements

What does c equal for


the following cases?
• a = 7; b = 0; 14

• a = 3; b = 1; 4

• a = 5; b = 0; ‘cat’

• a = -2; b = 1; -9
Example: Zeros of quadratic equation
Based on discriminant (value under the sqrt), a
quadratic equation could have 0, 1, or 2 real zeros
Nested if statements
 Can have any number of
nested if/else branches
 Follow the default tabbing;
otherwise it is difficult to
understand
 Evaluate each condition one
at a time, top-to-bottom

For example, if
 age = 25
 You are not single
 salary = 70,000
Then you would be living
in your own house
switch/case branches
Similar to if/else statements, but more efficient when a
branch could be selected under multiple conditions

Value to
compare to
the cases

If num== any of
values listed in the
cell array, then that
branch is chosen

“otherwise” performs
the role of “else”
try/catch branches
Useful for debugging or to compensate for user error
 If no errors, the try branch is processed and the catch branch ignored
 Once an error occurs, jump to the catch branch
While loops
Go through the loop until a condition becomes
false
 A while loop is a block of commands that are repeated
indefinitely as long as the condition is true
 Once the condition is false, the code continues after the end
statement
 The condition is only evaluated at the top of the loop:
 If the condition becomes false in the middle of the code block, the
code block is taken to completion
 Infinite loops are possible. To escape one, press ctrl+c in the
command window.
while loop
example
To track the progress of
each variable through a
loop, use a table like the
one below

error real guess


27 5 9
4 5 7
2 5 6
1 5 5.5
5
5

while loop example (array indexing)

Before entering the loop, what


will be stored in variable Bob?

[0 0 5]

If, for example, ind equals 4, what


Bob(4) = Bob(3) * 2 would this last statement do?
-Take the value in the 3rd index of vector Bob
-Multiply by 2
-Store result into the 4th index of Bob
while
loop
example
(vector)
ind Bob
3 [005]
4 [ 0 0 5 10 ]
5 [ 0 0 5 10 20 ]
6 [ 0 0 5 10 20 40 ]
7 [ 0 0 5 10 20 40 80 ]
Infinite loop example

q
5
6
7
8
9
 There will never be a time when
the condition is false 10

 To halt an infinite loop (or any
MATLAB operation), press Ctrl+c
in the Command Window
*that’s Command+c
on a Mac
Except where otherwise noted, this work is licensed under the Creative
Commons Attribution-NonCommercial 4.0 International License.

To view a copy of this license


• visit http://creativecommons.org/licenses/by-nc/4.0/
• or send a letter to Creative Commons, PO Box 1866, Mountain View,
CA 94042, USA.

Creative Commons and the double C in a circle are registered trademarks


of Creative Commons in the United States and other countries. Third party
marks and brands are the property of their respective holders.

You might also like