Transcript Powerpoint
•
ENG 1181
Logical Expressions in MATLAB
Chapter 6.1
Topics Covered:
1. Relational and Logical Operators
•
Between single values
•
Involving arrays
College of Engineering
Engineering Education Innovation Center
•
ENG 1181
192-
RELATIONAL OPERATORS
Relational operator
<
Meaning
Less than.
<=
Less than or equal to.
>
Greater than.
>=
Greater then or equal to.
==
Equal to.
~=
Not equal to.
Relational operators compare two numbers in a
comparison statement.
If the statement is TRUE, it is assigned a value of 1.
If the statement is FALSE, it is assigned a value of 0.
193
•
ENG 1181
193
RELATIONAL OPERATORS
>> 5 > 8
5 is not larger than 8 so the
answer is 0
ans =
0
5 is smaller than 10 so the
answer is 1
>> a = 5 < 10
a=
The answer (1) is stored in a
1
>> y = (6 < 10) + (7 > 8) + (5 * 3 = = 60 / 4)
y=
2
=1
=0
=1
More examples of relational operators can be
found on pg 193 of the text
•
ENG 1181
195
LOGICAL OPERATORS
Logical operators have numbers as operands.
A nonzero number is TRUE.
A zero number is FALSE.
Logical Operator
Name
Meaning
&
Example: A & B
AND
TRUE if both operands
(A and B) are true.
|
Example: A | B
OR
TRUE if either or both
operands (A and B) are true.
~
Example: ~ A
NOT
TRUE if the operand (A) is false.
FALSE if the operand (A) is true.
•
LOGICAL OPERATORS
>> 3 & 7
ans =
1
3, 7 are both TRUE (nonzero)
So (3 AND 7) is TRUE (1)
>> a = 5 | 0
a=
1
5 or 0
5 is TRUE, so the answer is 1
ENG 1181
195-
197
>> x = -2;
Define x
>> -5 < x < -1
ans =
0
-5 < x < -1 is mathematically correct, but MATLAB
returns FALSE (0). MATLAB executes from left to
right so the statement is equivalent to
(-5 < x) < -1
-5 < 1 is true (1), then 1 < -1 is false (0)
>> -5 < x & x < -1
ans =
1
Correct statement is obtained with the logical and
(&) operator. The inequalities are executed first.
Both are true so the answer in 1
•
ENG 1181
Expanded Order of Operations
Precedence
1
Operation
Parentheses (inner first if nested)
2
Exponentiation
3
Logical NOT (~)
4
Multiplication, Division
5
Addition, Subtraction
6
Relational Operators
( >, <. >=, <=, ==, ~= )
7
Logical AND ( &, && )
8
Logical OR ( |, || )
196
•
RELATIONAL OPERATORS
>> 5 + 4 > 8
ans =
Addition is done first,
so true (1)
1
>> 5 + (4>8)
ans =
4>8 is false, so add 0
5
>> y = ~1 & 0
y=
0
~ is performed first,
then &
More examples of order of operations can be
found on pg 197 of the text
ENG 1181
197
•
ENG 1181
193-
194
Arrays in Logical Expressions
Use of arrays in logical expressions will
produce an array of 1s and 0s using elementby-element comparisons
>> T=[23 34 25 67 56];
>>T>32
ans =
0 1 0 1 1
U=[0 5 6 0 0];
>>T&U
ans =
0 1 1 0 0
>>~(T&U)
ans =
1 0 0 1 1
>>sum(T>32)
ans =
3
>> find(T>32)
ans =
2 4 5
>>find(T>32 & T<60)
ans =
2 5
P. 8