SlideShare a Scribd company logo
Chapter 6
Programming in MATLAB
MATLAB An Introduction with Applications, 5th Edition
Dr. Amos Gilat
The Ohio State University
6.0
In this chapter will study how to
make MATLAB programs run
sections of code
• If something is true
• While something is true
• For a certain number of times
2
6.0
Will also learn how to run different
sections of code depending on
• The value of a variable
• Which particular condition is true
• What combination of conditions is true
– If this and that are true
– If this or that is true, etc.
• What relationship two things have
– For example, one is less than the other;
greater than; equal to; not equal to; etc.
3
6.1 Relational and Logical Operators
Relational operator:
• Can't put space between operators that have
two characters
• "Not equal to" is "~=", not "!=" as in C or C++
• "Equal to" comparison is two equal signs (==),
not one.
– Remember, "=" means "assign to" or "put into"
4
6.1 Relational and Logical Operators
• Result of comparing with a relational
operator is always "true" or "false"
– If "true", MATLAB gives the comparison a
value of one (1)
– If "false", MATLAB gives the comparison a
value of zero (0)
This may be different than convention
in other programming languages. For
example, C gives an expression that is
false a value of zero, but it can give a
true expression any value but zero,
which you can't assume will be one
5
6.1 Relational and Logical Operators
When comparing arrays
• They must be the same dimensions
• MATLAB does an elementwise
comparison
• Result is an array that has same
dimensions as other two but only
contains 1's and 0's
6
6.1 Relational and Logical Operators
When comparing array to scalar
• MATLAB compares scalar to every
member of array
• Result is an array that has same
dimensions as original but only
contains 1's and 0's
7
6.1 Relational and Logical Operators
Example
>> x=8:12
x = 8 9 10 11 12
>> x>10
ans = 0 0 0 1 1
>> x==11
ans = 0 0 0 1 0
>> x>=7
ans = 1 1 1 1 1
8
6.1 Relational and Logical Operators
It helps to picture in your mind that the result
of a logical comparison
1. Is a vector
2. Has a 0 or 1 corresponding to each original
element
>> x=8:12
x = 8 9 10 11 12
>> x>10
ans = 0 0 0 1 1
9
T I P
6.1 Relational and Logical Operators
If results of relational comparison
stored in a vector, can easily find the
number of elements that satisfy that
comparison, i.e., that are true, by using
sum command, which returns sum of
vector elements
• Works because elements that are true
have value of one and false elements
have value zero
10
T I P
6.1 Relational and Logical Operators
EXAMPLE
How many of the numbers from 1-20
are prime?
• Use MATLAB isprime command, which
returns true (1) is number is prime and
false (0) if it isn't
>> numbers = 1:20;
>> sum( isprime(numbers) )
ans =
8
11
T I P
6.1 Relational and Logical Operators
Can mix relational and arithmetic
operations in one expression
• Arithmetic operations follow usual
precedence and always have higher
precedence than relational operations
• Relational operations all have equal
precedence and evaluated left to right
12
T I P
6.1 Relational and Logical Operators
A logical vector or logical array is a
vector/array that has only logical
1's and 0's
• 1's and 0's from mathematical operations
don't count
• 1's and 0's from relational comparisons do
work
• First time a logical vector/array used in
arithmetic, MATLAB changes it to a
numerical vector/array
13
6.1 Relational and Logical Operators
Can use logical vector to get actual values
that satisfy relation, not just whether or
not relation satisfied. Doing this is called
logical indexing or logical subscripting
• Do this by using logical vector as index in
vector of values. Result is values that satisfy
relation, i.e., values for which relationship
are 1
• NOTE – technique doesn't quite work with arrays.
Won't discuss that case further
14
6.1 Relational and Logical Operators
EXAMPLE
What are the numbers from 1-10 that are
multiples of 3?
>> numbers = 1:10
numbers = 1 2 3 4 5 6 7 8 9 10
>> multiples = rem( numbers, 3 ) == 0
multiples = 0 0 1 0 0 1 0 0 1 0
>> multiplesOf3 = numbers(multiples)
multiplesOf3 =
3 6 9
15
6.1 Relational and Logical Operators
Example
Think of numbers(multiples) as pulling
out of numbers all elements that have a 1 in
the corresponding element of multiples
numbers = 1 2 3 4 5 6 7 8 9 10
multiples = 0 0 1 0 0 1 0 0 1 0
numbers(multiples) = 3 6 9
16
6.1 Relational and Logical Operators
EXAMPLE
What are the prime numbers from 1-20?
>> numbers = 1:20;
>> numbers( isprime(numbers) )
ans =
2 3 5 7 11 13 17 19
Logical indexing is particularly useful when
used with logical operators, discussed next
17
6.1 Relational and Logical Operators
Logical operators:
Boolean logic is a system for combining
expressions that are either true of false.
• MATLAB has operators and commands
to do many Boolean operations
• Boolean operations in combination with
relational commands let you perform
certain types of computations clearly
and efficiently
18
6.1 Relational and Logical Operators
A truth table defines the laws of Boolean
logic. It gives the output of a logical
operation for every possible combination of
inputs. The truth table relevant to MATLAB
is
19
6.1 Relational and Logical Operators
In words, the truth table says
• AND is true if both inputs are true,
otherwise it is false
• OR is true if at least one input is true,
otherwise it is false
• XOR (exclusive OR) is true if exactly one
input is true, otherwise it is false
• NOT is true if the input is false,
otherwise it is false
20
6.1 Relational and Logical Operators
An arithmetic operator, e.g., + or -, is a
symbol that causes MATLAB to perform an
arithmetical operation using the numbers
or expressions on either side of the symbol
Similarly, a logical operator is a character
that makes MATLAB perform a logical
operation on one or two numbers or
expressions
21
6.1 Relational and Logical Operators
MATLAB has three logical operators: &, |, ~
• a&b does the logical AND operation on a and b
• a|b does the logical OR operation on a or b
• ~a does the logical NOT operation on a
• Arguments to all logical operators are numbers
– Zero is "false"
– Any non-zero number is "true"
• Result (output) of logical operator is a logical one
(true) or zero (false)
22
6.1 Relational and Logical Operators
When using logical operator on arrays
• They must be the same dimensions
• MATLAB does an element-wise evaluation of
operator
• Result is an array that has same dimensions
as other two but only contains 1's and 0's
(not only operates on one array so the
first point is irrelevant)
23
6.1 Relational and Logical Operators
When operating with array and scalar
• MATLAB does element-wise operation
on each array element with scalar
• Result is an array that has same
dimensions as original but only contains
1's and 0's
24
6.1 Relational and Logical Operators
Can combine arithmetic, relational
operators, and logical operators. Order
of precedence is
25
6.1 Relational and Logical Operators
EXAMPLE
Child – 12 or less years
Teenager – more than 12 and less than 20 years
Adult – 20 or more years
>> age=[45 47 15 13 11]
age = 45 47 15 13 11
26
6.1 Relational and Logical Operators
EXAMPLE
Who is a teenager?
>> age=[45 47 15 13 11];
>> age>=13
ans = 1 1 1 1 0
>> age<=19
ans = 0 0 1 1 1
>> age>=13 & age<=19
ans = 0 0 1 1 0
27
These mark the two teenagers
6.1 Relational and Logical Operators
EXAMPLE
>> age=[45 47 15 13 11]
age = 45 47 15 13 11
Who is not a teenager?
>> ~(age>=13 & age<=19)
ans = 1 1 0 0 1
Who is an adult or a child?
>> age>19 | age<13
ans = 1 1 0 0 1
28
6.1 Relational and Logical Operators
Built-in logical functions:
MATLAB has some built-in functions or
commands for doing logical operations and
related calculations. Three are equivalent
to the logical operators
• and(A,B) – same as A&B
• or(A,B) – same as A|B
• not(A) – same as ~A
29
6.1 Relational and Logical Operators
MATLAB also has
other Boolean
functions
30
6.2 Conditional Statements
A conditional statement is a command
that allows MATLAB to decide whether
or not to execute some code that
follows the statement
• Conditional statements almost always
part of scripts or functions
• They have three general forms
– if-end
– if-else-end
– if-elseif-else-end
31
6.2.1 The if-end Structure
A flowchart is a diagram that shows the
code flow. It is particularly useful for
showing how conditional statements
work. Some common flowchart
symbols are
• represents a sequence of commands
• represents an if-statement
• shows the direction of code
execution
32
6.2.1 The if-end Structure
If the conditional expression is true,
MATLAB runs the lines of code that are
between the line with if and the line
with end. Then it continues with the
code after the end-line 33
6.2.1 The if-end Structure
If the conditional expression is false,
MATLAB skips the lines of code that are
between the line with if and the line with
end. Then it continues with the code after
the end-line 34
6.2.1 The if-end Structure
The conditional expression is true if it
evaluates to a logical 1 or to a non-zero
number. The conditional expression is false
if it evaluates to a logical 0 or to a
numerical zero 35
6.2.2 The if-else-end Structure
if-else-end structure lets you execute
one section of code if a condition is true and
a different section of code if it is false.
EXAMPLE - answering your phone
if the caller is your best friend
talk for a long time
else
talk for a short time
end
36
6.2.2 The if-else-end Structure
Fig. 6-2 shows the code and the
flowchart for the if-else-end
structure
37
6.2.3 The if-elseif-else-end Structure
if-elseif-else-end structure lets you
choose one of three (or more) sections of code
to execute
EXAMPLE - answering your phone
if the caller is your best friend
talk for a long time
elseif the caller is your study-mate
talk until you get the answer to the hard problem
else
say you'll call back later
end
38
6.2.3 The if-elseif-else-end Structure
Can have as many elseif statements as you want
EXAMPLE
if the caller is your best friend
talk for a long time
elseif the caller is a potential date
talk for a little bit and then set a time to meet
elseif the caller is your study-mate
talk until you get the answer to the hard problem
elseif the caller is your mom
say you're busy and can't talk
else
have your room-mate say you'll call back later
end
39
6.2.3 The if-elseif-else-end Structure
Fig. 6-3 shows the code and the flowchart for
the if-elseif-else-end structure
40
6.2.3 The if-elseif-else-end Structure
Can omit else statement
• In this case, if no match to if- or
elseif-statements, no code in
structure gets executed
41
6.3 The switch-case Statement
if-elseif-else-end structure
gets hard to read if more than a few
elseif statements. A clearer
alternative is the switch-case
structure
• switch-case slightly different
because choose code to execute
based on value of scalar or string, not
just true/false
42
6.3 The switch-case Statement
Concept is
switch name
case 'Bobby'
talk for a long time
case 'Susan'
talk for a little bit and then set a time to meet
case 'Hubert'
talk until you get the answer to the hard problem
case 'Mom'
say you're busy and can't talk
otherwise
have your room-mate say you'll call back later
end
43
6.3 The switch-case Statement
44
6.3 The switch-case Statement
switch evaluates
switch-expression
–If value is equal to
value1, executes
all commands up to
next case,
otherwise,
or end statement, i.e., Group 1
commands, then executes code after
end statement
–If value is equal to value2, same as
above but Group 2 commands only
–Etc. 45
6.3 The switch-case Statement
• If switch-expression not
equal to any of values in
case statement,
commands after
otherwise executed. If
otherwise not present,
no commands executed
• If switch expression matches more than one
case value, only first matching case executed
46
6.3 The switch-case Statement
Comparisons of text strings are case-
sensitive. If case values are text strings,
make all values either lower case or upper
case, then use upper or lower
command to convert switch expression
caller = lower( name );
switch caller
case 'bobby'
some code
case 'susan'
some code
case 'mom'
some code
end
47
T I P
6.4 Loops
A loop is another method of flow
control. A loop executes one set of
commands repeatedly. MATLAB has
two ways to control number of times
loop executes commands
• Method 1 – loop executes commands a
specified number of times
• Method 2 – loop executes commands as
long as a specified expression is true
48
6.4.1 for-end Loops
A for-end loop (often called a for-
loop) executes set of commands a
specified number of times. The set of
commands is called the body of the
loop
49
6.4.1 for-end Loops
• The loop index variable can have any
variable name (usually i, j, k, m, and n
are used)
– i and j should not be used when working
with complex numbers. (ii and jj are good
alternative names)
50
Body of loop
6.4.1 for-end Loops
1. Loop sets k to f,
and executes
commands between
for and the end commands,
i.e., executes body of loop
2. Loop sets k to f+s, executes body
3. Process repeats itself until k > t
4. Program then continues with commands
that follow end command
• f and t are usually integers
• s usually omitted. If so, loop uses
increment of 1
51
Body of loop
6.4.1 for-end Loops
• Increment s can be negative
– For example, k = 25:–5:10 produces four
passes with k = 25, 20, 15, 10
• If f = t, loop executes once
• If f > t and s > 0, or if f < t and
s < 0, loop not executed
52
Body of loop
6.4.1 for-end Loops
• If values of k, s, and t are such that k cannot
be equal to t, then
– If s positive, last pass is one where k has largest
value smaller than t
• For example, k = 8:10:50 produces five passes with
k = 8, 18, 28, 38, 48
– If s is negative, last pass is one where k has
smallest value larger than t
53
Body of loop
6.4.1 for-end Loops
• In the for command k can also be assigned
specific value (typed in as a vector)
– For example: for k = [7 9 –1 3 3 5]
• In general, loop body should not change value
of k
• Each for command in a program must have
an end command
54
Body of loop
6.4.1 for-end Loops
• Value of loop index variable (k) not
displayed automatically
– Can display value in each pass (sometimes
useful for debugging) by typing k as one of
commands in loop
• When loop ends, loop index variable (k)
has value last assigned to it
55
Body of loop
6.4.1 for-end Loops
EXAMPLE
Script
for k=1:3:10
k
x = k^2
end
fprintf('After loop k = %dn', k);
56
Output
k = 1
x = 1
k = 4
x = 16
k = 7
x = 49
k = 10
x = 100
After loop k = 10
6.4.1 for-end Loops
Can often calculate something
using either a for-loop or
elementwise operations.
Elementwise operations are:
• Often faster
• Often easier to read
• More MATLAB-like
GENERAL ADVICE – use
elementwise operations when you
can, for-loops when you have to
57
T I P
6.4.2 while-end Loops
while-end loop used when
• You don't know number of loop iterations
• You do have a condition that you can test and
stop looping when it is false. For example,
– Keep reading data from a file until you reach the
end of the file
– Keep adding terms to a sum until the difference
of the last two terms is less than a certain
amount
58
6.4.2 while-end Loops
1. Loop
evaluates
conditional-expression
2. If conditional-expression is true,
executes code in body, then goes
back to Step 1
3. If conditional-expression is false,
skips code in body and goes to code
after end-statement
59
6.4.2 while-end Loops
The conditional expression of a while-
end loop
• Has a variable in it
– Body of loop must change value of variable
– There must be some value of the variable that
makes the conditional expression be false
60
6.4.2 while-end Loops
EXAMPLE
This script
x = 1
while x <= 15
x = 2*x
end
61
Makes this output
x =
1
x =
2
x =
4
x =
8
x =
16
6.4.2 while-end Loops
If the conditional expression never
becomes false, the loop will keep
executing... forever! The book calls this
an indefinite loop, but more commonly
referred to as an infinite loop. Your
program will just keep running, and if
there is no output from the loop (as if
often the case), it will look like MATLAB
has stopped responding
62
6.4.2 while-end Loops
Common causes of indefinite loops:
• No variable in conditional expression
distance1 = 1;
distance2 = 10;
distance3 = 0;
while distance1 < distance2
fprintf('Distance = %dn',distance3);
end
63
distance1 and distance2
never change
6.4.2 while-end Loops
Common causes of indefinite loops:
• Variable in conditional expression never
changes
minDistance = 42;
distanceIncrement = 0;
distance = 0;
while distance < minDistance
distance=distance+distanceIncrement;
end
64
Typo – should be 10
6.4.2 while-end Loops
Common causes of indefinite loops:
• Wrong variable in conditional expression
changed
minDistance = 42;
delta = 10;
distance = 0;
while distance < minDistance
minDistance = minDistance + delta;
end
65
Typo – should be distance
6.4.2 while-end Loops
Common causes of indefinite loops:
• Conditional expression never becomes false
minDistance = 42;
x = 0;
y = 0;
while -sqrt( x^2+y^2 ) < minDistance
x = x + 1;
y = y + x;
end
66
Typo – shouldn't be
any negative sign
6.4.2 while-end Loops
If your program gets caught in an
indefinite loop,
• Put the cursor in the Command
Window
• Press CTRL+C
67
T I P
6.5 Nested Loops and Nested Conditional Statements
If a loop or conditional statement is
placed inside another loop or
conditional statement, the former are
said to be nested in the latter.
• Most common to hear of a nested loop,
i.e., a loop within a loop
– Often occur when working with two-
dimensional problems
• Each loop and conditional statement must
have an end statement
68
6.5 Nested Loops and Nested Conditional Statements
EXAMPLE
69
6.6 THE break AND continue COMMANDS
The break command:
• When inside a loop (for and while), break
terminates execution of loop
– MATLAB jumps from break to end command
of loop, then continues with next command
(does not go back to the for or while
command of that loop).
– break ends whole loop, not just last pass
• If break inside nested loop, only nested
loop terminated (not any outer loops)
70
6.6 The break and continue Commands
–break command in script or function
file but not in a loop terminates
execution of file
–break command usually used within a
conditional statement.
• In loops provides way to end looping if some
condition is met
71
6.6 The break and continue Commands
EXAMPLE
Script
while( 1 )
name = input( 'Type name or q to quit: ', 's' );
if length( name ) == 1 && name(1) == 'q'
break;
else
fprintf( 'Your name is %sn', name );
end
end
72
Output for inputs of "Greg", "quentin", "q"
Type name or q to quit: Greg
Your name is Greg
Type name or q to quit: quentin
Your name is quentin
Type name or q to quit: q
>>
Trick – "1" is always true so it makes loop iterate forever!
If user entered only one
letter and it is a "q", jump
out of loop
Otherwise print name
Only way to exit loop!
6.6 The break and continue Commands
The continue command:
Use continue inside a loop (for- and while-)
to stop current iteration and start next iteration
– continue usually part of a conditional
statement. When MATLAB reaches continue it
does not execute remaining commands in loop
but skips to the end command of loop and then
starts a new iteration
73
6.6 The break and continue Commands
EXAMPLE
for ii=1:100
if rem( ii, 8 ) == 0
count = 0;
fprintf('ii=%dn',ii);
continue;
end
% code
% more code
end
74
Every eight iteration reset
count to zero, print the
iteration number, and skip
the remaining
computations in the loop

More Related Content

What's hot

Matrices and determinants
Matrices and determinantsMatrices and determinants
Matrices and determinants
som allul
 
Determinants
DeterminantsDeterminants
Determinants
Seyid Kadher
 
matrix algebra
matrix algebramatrix algebra
matrix algebra
kganu
 
presentation on matrix
 presentation on matrix presentation on matrix
presentation on matrix
Nikhi Jain
 
Ppt on matrices and Determinants
Ppt on matrices and DeterminantsPpt on matrices and Determinants
Ppt on matrices and Determinants
NirmalaSolapur
 
Chapter 4: Linear Algebraic Equations
Chapter 4: Linear Algebraic EquationsChapter 4: Linear Algebraic Equations
Chapter 4: Linear Algebraic Equations
Maria Fernanda
 
R.Ganesh Kumar
R.Ganesh KumarR.Ganesh Kumar
R.Ganesh Kumar
GaneshKumar1103
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
Dun Automation Academy
 
Matrices ppt
Matrices pptMatrices ppt
Matrices ppt
aakashray33
 
Matrices
MatricesMatrices
Matrices
ashishtqm
 
Matrices 1
Matrices 1Matrices 1
Matrices 1
Andrew Grichting
 
Matrices & determinants
Matrices & determinantsMatrices & determinants
Matrices & determinants
indu thakur
 
Arrays in c unit iii chapter 1 mrs.sowmya jyothi
Arrays in c unit iii chapter 1 mrs.sowmya jyothiArrays in c unit iii chapter 1 mrs.sowmya jyothi
Arrays in c unit iii chapter 1 mrs.sowmya jyothi
Sowmya Jyothi
 
Matrix Operations
Matrix OperationsMatrix Operations
Matrix Operations
Ron Eick
 
Lesson 1 matrix
Lesson 1 matrixLesson 1 matrix
Lesson 1 matrix
Melvy Dela Torre
 
MATRICES
MATRICESMATRICES
MATRICES
faijmsk
 
Introduction to Matrices
Introduction to MatricesIntroduction to Matrices
Introduction to Matrices
holmsted
 
Matrix.
Matrix.Matrix.
Matrix.
Awais Bakshy
 
Matrix presentation By DHEERAJ KATARIA
Matrix presentation By DHEERAJ KATARIAMatrix presentation By DHEERAJ KATARIA
Matrix presentation By DHEERAJ KATARIA
Dheeraj Kataria
 

What's hot (19)

Matrices and determinants
Matrices and determinantsMatrices and determinants
Matrices and determinants
 
Determinants
DeterminantsDeterminants
Determinants
 
matrix algebra
matrix algebramatrix algebra
matrix algebra
 
presentation on matrix
 presentation on matrix presentation on matrix
presentation on matrix
 
Ppt on matrices and Determinants
Ppt on matrices and DeterminantsPpt on matrices and Determinants
Ppt on matrices and Determinants
 
Chapter 4: Linear Algebraic Equations
Chapter 4: Linear Algebraic EquationsChapter 4: Linear Algebraic Equations
Chapter 4: Linear Algebraic Equations
 
R.Ganesh Kumar
R.Ganesh KumarR.Ganesh Kumar
R.Ganesh Kumar
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
Matrices ppt
Matrices pptMatrices ppt
Matrices ppt
 
Matrices
MatricesMatrices
Matrices
 
Matrices 1
Matrices 1Matrices 1
Matrices 1
 
Matrices & determinants
Matrices & determinantsMatrices & determinants
Matrices & determinants
 
Arrays in c unit iii chapter 1 mrs.sowmya jyothi
Arrays in c unit iii chapter 1 mrs.sowmya jyothiArrays in c unit iii chapter 1 mrs.sowmya jyothi
Arrays in c unit iii chapter 1 mrs.sowmya jyothi
 
Matrix Operations
Matrix OperationsMatrix Operations
Matrix Operations
 
Lesson 1 matrix
Lesson 1 matrixLesson 1 matrix
Lesson 1 matrix
 
MATRICES
MATRICESMATRICES
MATRICES
 
Introduction to Matrices
Introduction to MatricesIntroduction to Matrices
Introduction to Matrices
 
Matrix.
Matrix.Matrix.
Matrix.
 
Matrix presentation By DHEERAJ KATARIA
Matrix presentation By DHEERAJ KATARIAMatrix presentation By DHEERAJ KATARIA
Matrix presentation By DHEERAJ KATARIA
 

Similar to Matlab ch1 (1)

3.pdf
3.pdf3.pdf
Mbd dd
Mbd ddMbd dd
ET DAH SI HAN HAN ADIKNYA SI WIDIANTORO RIBUT MULU SAMA ABANG WIDI
ET DAH SI HAN HAN ADIKNYA SI WIDIANTORO RIBUT MULU SAMA ABANG WIDIET DAH SI HAN HAN ADIKNYA SI WIDIANTORO RIBUT MULU SAMA ABANG WIDI
ET DAH SI HAN HAN ADIKNYA SI WIDIANTORO RIBUT MULU SAMA ABANG WIDI
IrlanMalik
 
Chapter 3:Programming with Java Operators and Strings
Chapter 3:Programming with Java Operators and  StringsChapter 3:Programming with Java Operators and  Strings
Chapter 3:Programming with Java Operators and Strings
It Academy
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
It Academy
 
Chapter 3 : Programming with Java Operators and Strings
Chapter 3 : Programming with Java Operators and  StringsChapter 3 : Programming with Java Operators and  Strings
Chapter 3 : Programming with Java Operators and Strings
It Academy
 
Assignment On Matlab
Assignment On MatlabAssignment On Matlab
Assignment On Matlab
Miranda Anderson
 
5th chapter Relational algebra.pptx
5th chapter Relational algebra.pptx5th chapter Relational algebra.pptx
5th chapter Relational algebra.pptx
kavitha623544
 
Operators and Expressions in C++
Operators and Expressions in C++Operators and Expressions in C++
Operators and Expressions in C++
Praveen M Jigajinni
 
Matlab for marketing people
Matlab for marketing peopleMatlab for marketing people
Matlab for marketing people
Toshiaki Takeuchi
 
OCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & StatementsOCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & Statements
İbrahim Kürce
 
operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++
sanya6900
 
Matlab practical ---4.pdf
Matlab practical ---4.pdfMatlab practical ---4.pdf
Matlab practical ---4.pdf
Central university of Haryana
 
it skill excel sheet for ppt.pptx
it skill excel sheet for ppt.pptxit skill excel sheet for ppt.pptx
it skill excel sheet for ppt.pptx
MdAquibRazi1
 
chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)
It Academy
 
Logical vectors
Logical vectorsLogical vectors
Logical vectors
Ketan Paithankar
 
Using Excel Functions
Using Excel FunctionsUsing Excel Functions
Using Excel Functions
Gautam Gupta
 
On if,countif,countifs,sumif,countifs,lookup,v lookup,index,match
On if,countif,countifs,sumif,countifs,lookup,v lookup,index,matchOn if,countif,countifs,sumif,countifs,lookup,v lookup,index,match
On if,countif,countifs,sumif,countifs,lookup,v lookup,index,match
Rakesh Sah
 
Oop using JAVA
Oop using JAVAOop using JAVA
Oop using JAVA
umardanjumamaiwada
 
logical operators.pptx
logical operators.pptxlogical operators.pptx
logical operators.pptx
ParulBhatia37
 

Similar to Matlab ch1 (1) (20)

3.pdf
3.pdf3.pdf
3.pdf
 
Mbd dd
Mbd ddMbd dd
Mbd dd
 
ET DAH SI HAN HAN ADIKNYA SI WIDIANTORO RIBUT MULU SAMA ABANG WIDI
ET DAH SI HAN HAN ADIKNYA SI WIDIANTORO RIBUT MULU SAMA ABANG WIDIET DAH SI HAN HAN ADIKNYA SI WIDIANTORO RIBUT MULU SAMA ABANG WIDI
ET DAH SI HAN HAN ADIKNYA SI WIDIANTORO RIBUT MULU SAMA ABANG WIDI
 
Chapter 3:Programming with Java Operators and Strings
Chapter 3:Programming with Java Operators and  StringsChapter 3:Programming with Java Operators and  Strings
Chapter 3:Programming with Java Operators and Strings
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Chapter 3 : Programming with Java Operators and Strings
Chapter 3 : Programming with Java Operators and  StringsChapter 3 : Programming with Java Operators and  Strings
Chapter 3 : Programming with Java Operators and Strings
 
Assignment On Matlab
Assignment On MatlabAssignment On Matlab
Assignment On Matlab
 
5th chapter Relational algebra.pptx
5th chapter Relational algebra.pptx5th chapter Relational algebra.pptx
5th chapter Relational algebra.pptx
 
Operators and Expressions in C++
Operators and Expressions in C++Operators and Expressions in C++
Operators and Expressions in C++
 
Matlab for marketing people
Matlab for marketing peopleMatlab for marketing people
Matlab for marketing people
 
OCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & StatementsOCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & Statements
 
operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++
 
Matlab practical ---4.pdf
Matlab practical ---4.pdfMatlab practical ---4.pdf
Matlab practical ---4.pdf
 
it skill excel sheet for ppt.pptx
it skill excel sheet for ppt.pptxit skill excel sheet for ppt.pptx
it skill excel sheet for ppt.pptx
 
chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)
 
Logical vectors
Logical vectorsLogical vectors
Logical vectors
 
Using Excel Functions
Using Excel FunctionsUsing Excel Functions
Using Excel Functions
 
On if,countif,countifs,sumif,countifs,lookup,v lookup,index,match
On if,countif,countifs,sumif,countifs,lookup,v lookup,index,matchOn if,countif,countifs,sumif,countifs,lookup,v lookup,index,match
On if,countif,countifs,sumif,countifs,lookup,v lookup,index,match
 
Oop using JAVA
Oop using JAVAOop using JAVA
Oop using JAVA
 
logical operators.pptx
logical operators.pptxlogical operators.pptx
logical operators.pptx
 

More from mohsinggg

Matlab ch1 (6)
Matlab ch1 (6)Matlab ch1 (6)
Matlab ch1 (6)
mohsinggg
 
Matlab ch1 (5)
Matlab ch1 (5)Matlab ch1 (5)
Matlab ch1 (5)
mohsinggg
 
Matlab ch1 (3)
Matlab ch1 (3)Matlab ch1 (3)
Matlab ch1 (3)
mohsinggg
 
Matlab ch1 (2)
Matlab ch1 (2)Matlab ch1 (2)
Matlab ch1 (2)
mohsinggg
 
Cv writing
Cv writingCv writing
Cv writing
mohsinggg
 
History of black hole
History of black holeHistory of black hole
History of black hole
mohsinggg
 

More from mohsinggg (6)

Matlab ch1 (6)
Matlab ch1 (6)Matlab ch1 (6)
Matlab ch1 (6)
 
Matlab ch1 (5)
Matlab ch1 (5)Matlab ch1 (5)
Matlab ch1 (5)
 
Matlab ch1 (3)
Matlab ch1 (3)Matlab ch1 (3)
Matlab ch1 (3)
 
Matlab ch1 (2)
Matlab ch1 (2)Matlab ch1 (2)
Matlab ch1 (2)
 
Cv writing
Cv writingCv writing
Cv writing
 
History of black hole
History of black holeHistory of black hole
History of black hole
 

Recently uploaded

UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
pavan998932
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Undress Baby
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 

Recently uploaded (20)

UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 

Matlab ch1 (1)

  • 1. Chapter 6 Programming in MATLAB MATLAB An Introduction with Applications, 5th Edition Dr. Amos Gilat The Ohio State University
  • 2. 6.0 In this chapter will study how to make MATLAB programs run sections of code • If something is true • While something is true • For a certain number of times 2
  • 3. 6.0 Will also learn how to run different sections of code depending on • The value of a variable • Which particular condition is true • What combination of conditions is true – If this and that are true – If this or that is true, etc. • What relationship two things have – For example, one is less than the other; greater than; equal to; not equal to; etc. 3
  • 4. 6.1 Relational and Logical Operators Relational operator: • Can't put space between operators that have two characters • "Not equal to" is "~=", not "!=" as in C or C++ • "Equal to" comparison is two equal signs (==), not one. – Remember, "=" means "assign to" or "put into" 4
  • 5. 6.1 Relational and Logical Operators • Result of comparing with a relational operator is always "true" or "false" – If "true", MATLAB gives the comparison a value of one (1) – If "false", MATLAB gives the comparison a value of zero (0) This may be different than convention in other programming languages. For example, C gives an expression that is false a value of zero, but it can give a true expression any value but zero, which you can't assume will be one 5
  • 6. 6.1 Relational and Logical Operators When comparing arrays • They must be the same dimensions • MATLAB does an elementwise comparison • Result is an array that has same dimensions as other two but only contains 1's and 0's 6
  • 7. 6.1 Relational and Logical Operators When comparing array to scalar • MATLAB compares scalar to every member of array • Result is an array that has same dimensions as original but only contains 1's and 0's 7
  • 8. 6.1 Relational and Logical Operators Example >> x=8:12 x = 8 9 10 11 12 >> x>10 ans = 0 0 0 1 1 >> x==11 ans = 0 0 0 1 0 >> x>=7 ans = 1 1 1 1 1 8
  • 9. 6.1 Relational and Logical Operators It helps to picture in your mind that the result of a logical comparison 1. Is a vector 2. Has a 0 or 1 corresponding to each original element >> x=8:12 x = 8 9 10 11 12 >> x>10 ans = 0 0 0 1 1 9 T I P
  • 10. 6.1 Relational and Logical Operators If results of relational comparison stored in a vector, can easily find the number of elements that satisfy that comparison, i.e., that are true, by using sum command, which returns sum of vector elements • Works because elements that are true have value of one and false elements have value zero 10 T I P
  • 11. 6.1 Relational and Logical Operators EXAMPLE How many of the numbers from 1-20 are prime? • Use MATLAB isprime command, which returns true (1) is number is prime and false (0) if it isn't >> numbers = 1:20; >> sum( isprime(numbers) ) ans = 8 11 T I P
  • 12. 6.1 Relational and Logical Operators Can mix relational and arithmetic operations in one expression • Arithmetic operations follow usual precedence and always have higher precedence than relational operations • Relational operations all have equal precedence and evaluated left to right 12 T I P
  • 13. 6.1 Relational and Logical Operators A logical vector or logical array is a vector/array that has only logical 1's and 0's • 1's and 0's from mathematical operations don't count • 1's and 0's from relational comparisons do work • First time a logical vector/array used in arithmetic, MATLAB changes it to a numerical vector/array 13
  • 14. 6.1 Relational and Logical Operators Can use logical vector to get actual values that satisfy relation, not just whether or not relation satisfied. Doing this is called logical indexing or logical subscripting • Do this by using logical vector as index in vector of values. Result is values that satisfy relation, i.e., values for which relationship are 1 • NOTE – technique doesn't quite work with arrays. Won't discuss that case further 14
  • 15. 6.1 Relational and Logical Operators EXAMPLE What are the numbers from 1-10 that are multiples of 3? >> numbers = 1:10 numbers = 1 2 3 4 5 6 7 8 9 10 >> multiples = rem( numbers, 3 ) == 0 multiples = 0 0 1 0 0 1 0 0 1 0 >> multiplesOf3 = numbers(multiples) multiplesOf3 = 3 6 9 15
  • 16. 6.1 Relational and Logical Operators Example Think of numbers(multiples) as pulling out of numbers all elements that have a 1 in the corresponding element of multiples numbers = 1 2 3 4 5 6 7 8 9 10 multiples = 0 0 1 0 0 1 0 0 1 0 numbers(multiples) = 3 6 9 16
  • 17. 6.1 Relational and Logical Operators EXAMPLE What are the prime numbers from 1-20? >> numbers = 1:20; >> numbers( isprime(numbers) ) ans = 2 3 5 7 11 13 17 19 Logical indexing is particularly useful when used with logical operators, discussed next 17
  • 18. 6.1 Relational and Logical Operators Logical operators: Boolean logic is a system for combining expressions that are either true of false. • MATLAB has operators and commands to do many Boolean operations • Boolean operations in combination with relational commands let you perform certain types of computations clearly and efficiently 18
  • 19. 6.1 Relational and Logical Operators A truth table defines the laws of Boolean logic. It gives the output of a logical operation for every possible combination of inputs. The truth table relevant to MATLAB is 19
  • 20. 6.1 Relational and Logical Operators In words, the truth table says • AND is true if both inputs are true, otherwise it is false • OR is true if at least one input is true, otherwise it is false • XOR (exclusive OR) is true if exactly one input is true, otherwise it is false • NOT is true if the input is false, otherwise it is false 20
  • 21. 6.1 Relational and Logical Operators An arithmetic operator, e.g., + or -, is a symbol that causes MATLAB to perform an arithmetical operation using the numbers or expressions on either side of the symbol Similarly, a logical operator is a character that makes MATLAB perform a logical operation on one or two numbers or expressions 21
  • 22. 6.1 Relational and Logical Operators MATLAB has three logical operators: &, |, ~ • a&b does the logical AND operation on a and b • a|b does the logical OR operation on a or b • ~a does the logical NOT operation on a • Arguments to all logical operators are numbers – Zero is "false" – Any non-zero number is "true" • Result (output) of logical operator is a logical one (true) or zero (false) 22
  • 23. 6.1 Relational and Logical Operators When using logical operator on arrays • They must be the same dimensions • MATLAB does an element-wise evaluation of operator • Result is an array that has same dimensions as other two but only contains 1's and 0's (not only operates on one array so the first point is irrelevant) 23
  • 24. 6.1 Relational and Logical Operators When operating with array and scalar • MATLAB does element-wise operation on each array element with scalar • Result is an array that has same dimensions as original but only contains 1's and 0's 24
  • 25. 6.1 Relational and Logical Operators Can combine arithmetic, relational operators, and logical operators. Order of precedence is 25
  • 26. 6.1 Relational and Logical Operators EXAMPLE Child – 12 or less years Teenager – more than 12 and less than 20 years Adult – 20 or more years >> age=[45 47 15 13 11] age = 45 47 15 13 11 26
  • 27. 6.1 Relational and Logical Operators EXAMPLE Who is a teenager? >> age=[45 47 15 13 11]; >> age>=13 ans = 1 1 1 1 0 >> age<=19 ans = 0 0 1 1 1 >> age>=13 & age<=19 ans = 0 0 1 1 0 27 These mark the two teenagers
  • 28. 6.1 Relational and Logical Operators EXAMPLE >> age=[45 47 15 13 11] age = 45 47 15 13 11 Who is not a teenager? >> ~(age>=13 & age<=19) ans = 1 1 0 0 1 Who is an adult or a child? >> age>19 | age<13 ans = 1 1 0 0 1 28
  • 29. 6.1 Relational and Logical Operators Built-in logical functions: MATLAB has some built-in functions or commands for doing logical operations and related calculations. Three are equivalent to the logical operators • and(A,B) – same as A&B • or(A,B) – same as A|B • not(A) – same as ~A 29
  • 30. 6.1 Relational and Logical Operators MATLAB also has other Boolean functions 30
  • 31. 6.2 Conditional Statements A conditional statement is a command that allows MATLAB to decide whether or not to execute some code that follows the statement • Conditional statements almost always part of scripts or functions • They have three general forms – if-end – if-else-end – if-elseif-else-end 31
  • 32. 6.2.1 The if-end Structure A flowchart is a diagram that shows the code flow. It is particularly useful for showing how conditional statements work. Some common flowchart symbols are • represents a sequence of commands • represents an if-statement • shows the direction of code execution 32
  • 33. 6.2.1 The if-end Structure If the conditional expression is true, MATLAB runs the lines of code that are between the line with if and the line with end. Then it continues with the code after the end-line 33
  • 34. 6.2.1 The if-end Structure If the conditional expression is false, MATLAB skips the lines of code that are between the line with if and the line with end. Then it continues with the code after the end-line 34
  • 35. 6.2.1 The if-end Structure The conditional expression is true if it evaluates to a logical 1 or to a non-zero number. The conditional expression is false if it evaluates to a logical 0 or to a numerical zero 35
  • 36. 6.2.2 The if-else-end Structure if-else-end structure lets you execute one section of code if a condition is true and a different section of code if it is false. EXAMPLE - answering your phone if the caller is your best friend talk for a long time else talk for a short time end 36
  • 37. 6.2.2 The if-else-end Structure Fig. 6-2 shows the code and the flowchart for the if-else-end structure 37
  • 38. 6.2.3 The if-elseif-else-end Structure if-elseif-else-end structure lets you choose one of three (or more) sections of code to execute EXAMPLE - answering your phone if the caller is your best friend talk for a long time elseif the caller is your study-mate talk until you get the answer to the hard problem else say you'll call back later end 38
  • 39. 6.2.3 The if-elseif-else-end Structure Can have as many elseif statements as you want EXAMPLE if the caller is your best friend talk for a long time elseif the caller is a potential date talk for a little bit and then set a time to meet elseif the caller is your study-mate talk until you get the answer to the hard problem elseif the caller is your mom say you're busy and can't talk else have your room-mate say you'll call back later end 39
  • 40. 6.2.3 The if-elseif-else-end Structure Fig. 6-3 shows the code and the flowchart for the if-elseif-else-end structure 40
  • 41. 6.2.3 The if-elseif-else-end Structure Can omit else statement • In this case, if no match to if- or elseif-statements, no code in structure gets executed 41
  • 42. 6.3 The switch-case Statement if-elseif-else-end structure gets hard to read if more than a few elseif statements. A clearer alternative is the switch-case structure • switch-case slightly different because choose code to execute based on value of scalar or string, not just true/false 42
  • 43. 6.3 The switch-case Statement Concept is switch name case 'Bobby' talk for a long time case 'Susan' talk for a little bit and then set a time to meet case 'Hubert' talk until you get the answer to the hard problem case 'Mom' say you're busy and can't talk otherwise have your room-mate say you'll call back later end 43
  • 44. 6.3 The switch-case Statement 44
  • 45. 6.3 The switch-case Statement switch evaluates switch-expression –If value is equal to value1, executes all commands up to next case, otherwise, or end statement, i.e., Group 1 commands, then executes code after end statement –If value is equal to value2, same as above but Group 2 commands only –Etc. 45
  • 46. 6.3 The switch-case Statement • If switch-expression not equal to any of values in case statement, commands after otherwise executed. If otherwise not present, no commands executed • If switch expression matches more than one case value, only first matching case executed 46
  • 47. 6.3 The switch-case Statement Comparisons of text strings are case- sensitive. If case values are text strings, make all values either lower case or upper case, then use upper or lower command to convert switch expression caller = lower( name ); switch caller case 'bobby' some code case 'susan' some code case 'mom' some code end 47 T I P
  • 48. 6.4 Loops A loop is another method of flow control. A loop executes one set of commands repeatedly. MATLAB has two ways to control number of times loop executes commands • Method 1 – loop executes commands a specified number of times • Method 2 – loop executes commands as long as a specified expression is true 48
  • 49. 6.4.1 for-end Loops A for-end loop (often called a for- loop) executes set of commands a specified number of times. The set of commands is called the body of the loop 49
  • 50. 6.4.1 for-end Loops • The loop index variable can have any variable name (usually i, j, k, m, and n are used) – i and j should not be used when working with complex numbers. (ii and jj are good alternative names) 50 Body of loop
  • 51. 6.4.1 for-end Loops 1. Loop sets k to f, and executes commands between for and the end commands, i.e., executes body of loop 2. Loop sets k to f+s, executes body 3. Process repeats itself until k > t 4. Program then continues with commands that follow end command • f and t are usually integers • s usually omitted. If so, loop uses increment of 1 51 Body of loop
  • 52. 6.4.1 for-end Loops • Increment s can be negative – For example, k = 25:–5:10 produces four passes with k = 25, 20, 15, 10 • If f = t, loop executes once • If f > t and s > 0, or if f < t and s < 0, loop not executed 52 Body of loop
  • 53. 6.4.1 for-end Loops • If values of k, s, and t are such that k cannot be equal to t, then – If s positive, last pass is one where k has largest value smaller than t • For example, k = 8:10:50 produces five passes with k = 8, 18, 28, 38, 48 – If s is negative, last pass is one where k has smallest value larger than t 53 Body of loop
  • 54. 6.4.1 for-end Loops • In the for command k can also be assigned specific value (typed in as a vector) – For example: for k = [7 9 –1 3 3 5] • In general, loop body should not change value of k • Each for command in a program must have an end command 54 Body of loop
  • 55. 6.4.1 for-end Loops • Value of loop index variable (k) not displayed automatically – Can display value in each pass (sometimes useful for debugging) by typing k as one of commands in loop • When loop ends, loop index variable (k) has value last assigned to it 55 Body of loop
  • 56. 6.4.1 for-end Loops EXAMPLE Script for k=1:3:10 k x = k^2 end fprintf('After loop k = %dn', k); 56 Output k = 1 x = 1 k = 4 x = 16 k = 7 x = 49 k = 10 x = 100 After loop k = 10
  • 57. 6.4.1 for-end Loops Can often calculate something using either a for-loop or elementwise operations. Elementwise operations are: • Often faster • Often easier to read • More MATLAB-like GENERAL ADVICE – use elementwise operations when you can, for-loops when you have to 57 T I P
  • 58. 6.4.2 while-end Loops while-end loop used when • You don't know number of loop iterations • You do have a condition that you can test and stop looping when it is false. For example, – Keep reading data from a file until you reach the end of the file – Keep adding terms to a sum until the difference of the last two terms is less than a certain amount 58
  • 59. 6.4.2 while-end Loops 1. Loop evaluates conditional-expression 2. If conditional-expression is true, executes code in body, then goes back to Step 1 3. If conditional-expression is false, skips code in body and goes to code after end-statement 59
  • 60. 6.4.2 while-end Loops The conditional expression of a while- end loop • Has a variable in it – Body of loop must change value of variable – There must be some value of the variable that makes the conditional expression be false 60
  • 61. 6.4.2 while-end Loops EXAMPLE This script x = 1 while x <= 15 x = 2*x end 61 Makes this output x = 1 x = 2 x = 4 x = 8 x = 16
  • 62. 6.4.2 while-end Loops If the conditional expression never becomes false, the loop will keep executing... forever! The book calls this an indefinite loop, but more commonly referred to as an infinite loop. Your program will just keep running, and if there is no output from the loop (as if often the case), it will look like MATLAB has stopped responding 62
  • 63. 6.4.2 while-end Loops Common causes of indefinite loops: • No variable in conditional expression distance1 = 1; distance2 = 10; distance3 = 0; while distance1 < distance2 fprintf('Distance = %dn',distance3); end 63 distance1 and distance2 never change
  • 64. 6.4.2 while-end Loops Common causes of indefinite loops: • Variable in conditional expression never changes minDistance = 42; distanceIncrement = 0; distance = 0; while distance < minDistance distance=distance+distanceIncrement; end 64 Typo – should be 10
  • 65. 6.4.2 while-end Loops Common causes of indefinite loops: • Wrong variable in conditional expression changed minDistance = 42; delta = 10; distance = 0; while distance < minDistance minDistance = minDistance + delta; end 65 Typo – should be distance
  • 66. 6.4.2 while-end Loops Common causes of indefinite loops: • Conditional expression never becomes false minDistance = 42; x = 0; y = 0; while -sqrt( x^2+y^2 ) < minDistance x = x + 1; y = y + x; end 66 Typo – shouldn't be any negative sign
  • 67. 6.4.2 while-end Loops If your program gets caught in an indefinite loop, • Put the cursor in the Command Window • Press CTRL+C 67 T I P
  • 68. 6.5 Nested Loops and Nested Conditional Statements If a loop or conditional statement is placed inside another loop or conditional statement, the former are said to be nested in the latter. • Most common to hear of a nested loop, i.e., a loop within a loop – Often occur when working with two- dimensional problems • Each loop and conditional statement must have an end statement 68
  • 69. 6.5 Nested Loops and Nested Conditional Statements EXAMPLE 69
  • 70. 6.6 THE break AND continue COMMANDS The break command: • When inside a loop (for and while), break terminates execution of loop – MATLAB jumps from break to end command of loop, then continues with next command (does not go back to the for or while command of that loop). – break ends whole loop, not just last pass • If break inside nested loop, only nested loop terminated (not any outer loops) 70
  • 71. 6.6 The break and continue Commands –break command in script or function file but not in a loop terminates execution of file –break command usually used within a conditional statement. • In loops provides way to end looping if some condition is met 71
  • 72. 6.6 The break and continue Commands EXAMPLE Script while( 1 ) name = input( 'Type name or q to quit: ', 's' ); if length( name ) == 1 && name(1) == 'q' break; else fprintf( 'Your name is %sn', name ); end end 72 Output for inputs of "Greg", "quentin", "q" Type name or q to quit: Greg Your name is Greg Type name or q to quit: quentin Your name is quentin Type name or q to quit: q >> Trick – "1" is always true so it makes loop iterate forever! If user entered only one letter and it is a "q", jump out of loop Otherwise print name Only way to exit loop!
  • 73. 6.6 The break and continue Commands The continue command: Use continue inside a loop (for- and while-) to stop current iteration and start next iteration – continue usually part of a conditional statement. When MATLAB reaches continue it does not execute remaining commands in loop but skips to the end command of loop and then starts a new iteration 73
  • 74. 6.6 The break and continue Commands EXAMPLE for ii=1:100 if rem( ii, 8 ) == 0 count = 0; fprintf('ii=%dn',ii); continue; end % code % more code end 74 Every eight iteration reset count to zero, print the iteration number, and skip the remaining computations in the loop