CS 211 Lesson 5
Relational and Logical Operators
A man has integrity if his interest in the good of the service is at all times greater than his personal pride, and when he holds himself to the same line of duty when unobserved as he would follow if his superiors were present General S.L.A. Marshall
Understand the difference between relational and logical operators
Understand how MATLAB represents logical (true/false) values
Know the results produced by the AND, OR, XOR, and NOT logical operations
Be able to create logical expressions with relational and logical operators
I. MATLAB Concepts
A. Logical data type
MATLAB (since version 6.5) has a special data type called logical.
The logical data type has two possible values: true and false (these are also called Boolean values).
MATLAB stores a logical value in one byte (8 bits) of memory, even though only a single bit is needed.
The logical value of true is represented by the value 1 (or any non-zero value).
The logical value of false is represented by the value 0.
Some examples are shown below. Execute these statements in MATLAB and notice the difference between data types when using the values 0/1 and the values false/true. Note that using false/true is better style and saves memory!
CS211_Rocks = true;
CS211_Stinks = false;
Go_army = 0;
Go_airforce = 1;
Logical values may be scalars, vectors, or matrices -- one example of a logical matrix is shown below.
Truth_table = [true true; true false; false true; false false];
Logical values are generated by
relational operators -- which compare two values of the same data type, typically numbers
logical operators -- which combine multiple false/true values into a single false/true value
logical functions -- which return a logical false/true value
B. Relational operators
Recall that an operator is a symbol (one or two characters) used to perform some operation and return a resulting value.
Arithmetic operators (including + - * .* / ./ ^ .^) produce a numeric (by default, double) value.
Relational operators produce logical values and are:
< less than <= less than or equal to > greater than >= greater than or equal to == equal to (equivalent) ~= not equal
Make sure you understand the difference between the assignment operator (=) and the equality operator (==).
Relational operators produce a single logical value -- for example:
1 < 2
1 > 2
1 == 2
Count = 0 % notice the assignment statement! BAD if you meant comparison
Count == 1
When relational operators are used on arrays, the relational operator is applied element-by-element and produces a logical array with the same dimensions as the original operands -- for example:
[1 2 3] < [3 2 1]
'abcd' < 'cbaq'
[false false true] == [true false true]
[1 2; 3 4] > [5 6; 1 2]
[1 2 3 4] > [1 2] % error -- both operands must have the same dimensions
When used with char arrays, relational operators compare the 2-byte character encoding of each character -- note that:
' ' < '0'
'0' < 'a'
'A' < 'a'
'a' < 'b'
a space (blank) is "less than" all other printable characters
characters representing numerical digits are "less than" alphabetic characters
capital letters are "less than" lower case letters
the ordering of letters is as you would expect
Comparing strings (which are arrays of characters) with a relational operator is a bad idea. Instead, use the strcmp() function to compare strings.
'fuzzy' == 'wells'
'fred' == 'barney'
% works, but a bad idea; this produces an array of 5 false/true values
% error - the strings (arrays) are not of the same size
% correct way to compare strings - returns a single false/true value
If one operand is a scalar and the other an array, the scalar is compared with every element of the array -- for example:
5 < [2 4 6 8]
'm' < 'dog'
Relational operators have a lower precedence than arithmetic operators in the hierarchy of operations. For example, both of the expressions below produce the same results. However, the second one is considered better style and is easier to read. Use parentheses to make complex logical expressions more "readable".
7 + 3 < 15 - 2
(7 + 3) < (15 - 2)
Equality testing can lead to unexpected results due to round off errors in floating point calculations. For example, there is no way for a binary computer to exactly represent one-tenth (0.1)! To see this, execute the statement
When comparing two floating point numbers for equality, you should always test to see if their difference is less than some small number, as shown in the example below.
(500/(5000*sqrt(2))) == (600/(6000*sqrt(2)))
abs(500/(5000*sqrt(2))) - (600/(6000*sqrt(2))) < 1.0E-14
% should be true - but it's not!
% correct method - produces true!
C. Logical Operators
A logical operator has logical values (false/true) as operands and produces a single logical (false/true) value.
MATLAB's logical operators are:
& logical AND true only if both values are true && logical AND with shortcut evaluation true only if both values are true | logical OR true if either value is true || logical OR with shortcut evaluation true if either value is true ~ logical NOT, unary if true, then false; if false, then true
logical EXCLUSIVE OR (actually a logical function)
true only if both values are different
Consider the following examples:
x = input('Enter a value for x: ');
(x >= 0) && (x <= 10)
(x < 0) || (x > 10)
xor(x >= 0, x <= 10)
The shortcut operators (&&, ||) will stop the evaluation of an expression as soon as the results of the entire expression is known. A logical expression is always evaluated from left to right. Therefore, in some cases, the right-hand side operand can be ignored. This is very useful as you can see in the following examples, where the first, shortcut expression avoids a "division-by-zero" error, while the second expression generates an error.
(Count ~= 0) && (Total/Count > 80)
(Count ~= 0) & (Total/Count > 80)
When should you use the shortcut operators (&&, ||) and when should you use the non-shortcut operators (&, |)?
Always use the shortcut operators (&&, ||) when comparing single logical values (scalars).
Always use the non-shortcut operators (&, |) when comparing arrays of logical values
(Count ~= 0) && (Total/Count > 80)
(rand(1,3) > rand(1,3)) & ([3 5 9] > [5 2 6])
If a logical expression operand has a data type of double, non-zero values are converted to true and zero values are converted to false. (Typically you should avoid using logical expressions like the one below!)
5 && ~0
Logical operators have lower operator precedence than arithmetic and relational operators. However, always use parentheses to help make complex logical expressions easier to read.
7 + 3 < 15 - 2 && A == B
((7 + 3) < (15 - 2)) && (A == B)
% works as expected, but not easily "readable"
% better style
The precedence, from highest to lowest, of MATLAB's operators is:
the contents of parentheses are evaluated first starting with the innermost parentheses and working out
exponentials are evaluated working from left to right
multiplications and divisions are evaluated working from left to right
additions and subtractions are evaluated working from left to right
relational operators (< <= > >= == ~=) are evaluated working from left to right
logical not (~) is evaluated
logical and operators (& and &&) are evaluated working from left to right
logical or operators (| and ||) are evaluated working from left to right
D. Logical Functions
A logical function is a function that returns a logical value.
Some examples of built-in logical functions include:
II. Good Programming Practices
Always use the values false/true for logical values -- avoid using 0/1 for logical values.
Always add appropriate parentheses to complex logical expressions, even when they are not required, to make the expressions easier to read.
== to test for
Using an assignment operator (=) when you meant to test for equality (==) is probably the most common error in MATLAB programming.
Never test two double precision values for equality -- always test the absolute value of their difference to a small number (e.g., 1.0e-14)
A. Find the number of values in an array that are larger than some specific value
Compare each value in the array to the specific value and increment a "counter" each time the logical test is true.
This algorithm requires repetition and we don't know how to repeat statements yet!
MATLAB's built-in function algorithm
Generate an array of logical values that specifies which values in an array meet the criteria.
Sum up the number of logical values that were true.
Array > Specific_value
sum(Array > Specific_value)
produces an array of logical values
using the MATLAB built-in sum function, add all the logical values in the produced array. Since true values are equivalent to 1's, and false values are equivalent to 0's, we get the number of values in the Array that is greater than the Specific_value!
Try this example:
Array = rand(1,6);
Specific_value = input('Enter a value between 0 and 1: ');
Count = sum(Array > Specific_value);
fprintf('There are %d values greater than %g in the Array\n', Count, Specific_value);
Lab Work: Lab 5
References: Chapman Textbook: section 3.3