# Relational Operator - an overview (2023)

## Vectors and Matrices

Stormy Attaway, in MATLAB (Fifth Edition), 2019

### 2.4.1 Relational Expressions With Vectors and Matrices

Relational operators can be used with vectors and matrices. For example, let's say that there is a vector vec, and we want to compare every element in the vector to 5 to determine whether it is greater than 5 or not. The result would be a vector (with the same length as the original) with logical true or false values.

>> vec = [5 9 3 4 6 11];

>> isg = vec > 5

isg =

1×6logicalarray

010011

Note that this creates a vector consisting of all logical true or false values. Although the result is a vector of ones and zeros, and numerical operations can be done on the vector isg, its type is logical rather than double.

>> doubres = isg + 5

doubres =

565566

>> whos

NameSizeBytesClassAttributes

doubres1x648double

isg1x66logical

vec1x648double

To determine how many of the elements in the vector vec were greater than 5, the sum function could be used on the resulting vector isg:

>> sum(isg)

ans =

3

What we have done is to create a logical vector isg. This logical vector can be used to index into the original vector. For example, if only the elements from the vector that are greater than 5 are desired:

>> vec(isg)

ans =

9611

This is called logical indexing. Only the elements from vec for which the corresponding element in the logical vector isg is logical true are returned.

### Quick Question!

Why doesn’t the following work?

>> vec = [5 9 3 4 6 11];

>> v = [0 1 0 0 1 1];

>> vec(v)

Array indices must be positive integers or logical values.

The difference between the vector in this example and isg is that isg is a vector of logicals (logical 1s and 0s), whereas [0 1 0 0 1 1] by default is a vector of double values. Only logical 1s and 0s can be used to index into a vector. So, type casting the variable v would work:

>> v = logical(v);

>> vec(v)

ans =

9611

To create a vector or matrix of all logical 1s or 0s, the functions true and false can be used.

>> false(2)

ans =

00

00

>> true(1,5)

ans =

11111

Beginning with R2016a, the ones and zeros functions can also create logical arrays directly.

>> logone = ones(1,5, 'logical')

logone =

11111

>> class(logone)

ans =

logical

URL:

https://www.sciencedirect.com/science/article/pii/B9780128154793000027

## Introduction to MATLAB

Stormy Attaway, in MATLAB (Fifth Edition), 2019

### 1.6 Relational Expressions

Expressions that are conceptually either true or false are called relational expressions; they are also sometimes called Boolean expressions or logical expressions. These expressions can use both relational operators, which relate two expressions of compatible types, and logical operators, which operate on logical operands.

The relational operators in MATLAB are:

OperatorMeaning
>greater than
<less than
>=greater than or equals
<=less than or equals
==equality
~=inequality

All of these concepts should be familiar, although the actual operators used may be different from those used in other programming languages, or in mathematics classes. In particular, it is important to note that the operator for equality is two consecutive equal signs, not a single equal sign (as the single equal sign is already used as the assignment operator).

For numerical operands, the use of these operators is straightforward. For example, 3 < 5 means “3 less than 5”, which is, conceptually, a true expression. In MATLAB, as in many programming languages, “true” is represented by the logical value 1, and “false” is represented by the logical value 0. So, the expression 3 < 5 actually displays in the Command Window the value 1 (logical) in MATLAB. Displaying the result of expressions like this in the Command Window demonstrates the values of the expressions.

>> 3 < 5

ans =

logical

1

>> 2 > 9

ans =

logical

>> class(ans)

ans =

'logical'

The type of the result is logical, not double. MATLAB also has built-in true and false.

>> true

ans =

logical

1

In other words, true is equivalent to logical(1) and false is equivalent to logical(0).

Starting in R2016b, the output in the Command Window shows a header for most classes except for the default number type double, char, and string. If the type of a number result is not the default of double, the type (or class) is shown above the resulting value, as in the underlined “logical” in the previous expressions. However, in order to save room, these types will frequently not be shown for the rest of the book. Note: the class names char and string are not shown because the class is obvious from the single quotes (for char) or double quotes (for string).

Although these are logical values, mathematical operations could be performed on the resulting 1 or 0.

>> logresult = 5 < 7

logresult =

1

>> logresult + 3

ans =

4

Comparing characters (e.g., ‘a’ < ‘c’) is also possible. Characters are compared using their ASCII equivalent values in the character encoding. So, ‘a’ < ‘c’ is a true expression because the character ‘a’ comes before the character ‘c’.

>> 'a' < 'c'

ans =

1

The logical operators are:

OperatorMeaning
||or
&&and
~not

All logical operators operate on logical or Boolean operands. The not operator is a unary operator; the others are binary. The not operator will take a logical expression, which is true or false, and give the opposite value. For example, ~(3 < 5) is false as (3 < 5) is true. The or operator has two logical expressions as operands. The result is true if either or both of the operands are true, and false only if both operands are false. The and operator also operates on two logical operands. The result of an and expression is true only if both operands are true; it is false if either or both are false. The or/and operators shown here are used for scalars, or single values. Other or/and operators will be explained in Chapter 2.

The || and && operators in MATLAB are examples of operators that are known as short-circuit operators. What this means is that if the result of the expression can be determined based on the first part, then the second part will not even be evaluated. For example, in the expression:

2 < 4 || 'a' == 'c'

the first part, 2 < 4, is true so the entire expression is true; the second part ‘a’ == ‘c’ would not be evaluated.

In addition to these logical operators, MATLAB also has a function xor, which is the exclusive or function. It returns logical true if one (and only one) of the arguments is true. For example, in the following only the first argument is true, so the result is true:

>> xor(3 < 5, 'a' > 'c')

ans =

1

In this example, both arguments are true so the result is false:

>> xor(3 < 5, 'a' < 'c')

ans =

Given the logical values of true and false in variables x and y, the truth table (see Table 1.1) shows how the logical operators work for all combinations. Note that the logical operators are commutative (e.g., x || y is the same as y || x).

Table 1.1. Truth Table for Logical Operators

xy~xx || yx &amp;&amp; yxor(x,y)
TrueTrueFalseTrueTrueFalse
TrueFalseFalseTrueFalseTrue
FalseFalseTrueFalseFalseFalse

As with the numerical operators, it is important to know the operator precedence rules. Table 1.2 shows the rules for the operators that have been covered thus far in the order of precedence.

Table 1.2. Operator Precedence Rules

OperatorsPrecedence
Parentheses: ( )Highest
Power ˆ
Unary: negation (-), not (~)
Multiplication, division ⁎,/,\
Relational &lt;, &lt;=, &gt;, &gt;=, ==, ~=
And &amp;&amp;
Or ||Lowest

### Quick Question!

Assume that there is a variable x that has been initialized. What would be the value of the expression

3 < x < 5

if the value of x is 4? What if the value of x is 7?

The value of this expression will always be logical true, or 1, regardless of the value of the variable x. Expressions are evaluated from left to right. So, first the expression 3 < x will be evaluated. There are only two possibilities: either this will be true or false, which means that either the expression will have the logical value 1 or 0. Then, the rest of the expression will be evaluated, which will be either 1 < 5 or 0 < 5. Both of these expressions are true. So, the value of x does not matter: the expression 3 < x < 5 would be true regardless of the value of the variable x. This is a logical error; it would not enforce the desired range. If we wanted an expression that was logical true only if x was in the range from 3 to 5, we could write 3 < x && x < 5 (note that parentheses are not necessary).

### Practice 1.3

Think about what would be produced by the following expressions, and then type them in to verify your answers.

3 == 5 + 2

'b' < 'a' + 1

10 > 5 + 2

(10 > 5) + 2

'c' == 'd' - 1 && 2 < 4

'c' == 'd' - 1 || 2 > 4

xor('c' == 'd' - 1, 2 > 4)

xor('c' == 'd' - 1, 2 < 4)

10 > 5 > 2

Note: be careful about using the equality and inequality operators with numbers. Occasionally, roundoff errors appear, which means that numbers are close to their correct value but not exactly. For example, cos(pi/2) should be 0. However, because of a roundoff error, it is a very small number but not exactly 0.

>> cos(pi/2)

ans =

6.1232e-17

>> cos(pi/2) == 0

ans =

URL:

https://www.sciencedirect.com/science/article/pii/B9780128154793000015

## Packages and Use Clauses

Peter J. Ashenden, ... Darrell A. Teegarden, in The System Designer's Guide to VHDL-AMS, 2003

### Example

A package that provides signed arithmetic operations on integers represented as bit vectors might include a relational operator, defined as shown in Figure 10-11. The function negates the sign bit of each operand, then compares the resultant bit vectors using the predefined relational operator from the package standard. The full selected name for the predefined operator is necessary to distinguish it from the function being defined. If the return expression were written as “tmp1 < tmp2”, it would refer to the function in which it occurs, creating a circular definition.

URL:

https://www.sciencedirect.com/science/article/pii/B9781558607491500104

## Generalizing the Algebraic Operators

C.J. Date, ... Nikos A. Lorentzos, in Time and Relational Theory (Second Edition), 2014

### Exercises

11.1

In the body of the chapter we defined U_ versions of the regular relational operators, including operators like MATCHING that are fundamentally just shorthand. But what about the PACK and UNPACK shorthands? Would U_PACK and U_UNPACK operators make sense?

11.2

Does the following identity hold?

USING ( ACL ) : r1 INTERSECT r2

USING ( ACL ) : r1 MINUS ( USING ( ACL ) : r1 MINUS r2 )

11.3

Consider the operator U_JOIN. Assume for simplicity that the packing and unpacking are to be done on the basis of a single attribute A. Confirm that the following identity holds:

USING ( A ) : rl JOIN r2

WITH ( tl := r1 RENAME { A AS X },

t2 := r2 RENAME { A AS Y } ,

t3 := t1 JOIN t2 ,

t4 := t3 WHERE X OVERLAPS Y ,

t5 := EXTEND t4 : { A := X INTERSECT Y } ,

t6 := T5 { ALL BUT X , Y } ) :

PACK t6 ON ( A )

Confirm also that if r1 and r2 are initially packed on A, the final PACK step is unnecessary.

URL:

https://www.sciencedirect.com/science/article/pii/B9780128006313500113

## C Programming Essentials

Martin P. Bates, in Programming 8-bit PIC Microcontrollers in C, 2008

### Conditional Operations

Where a logical condition is tested in a while, if, or for statement, relational operators are used. One variable is compared with a set value or another variable, and the block is executed if the condition is true. The conditional operators are shown in Table 2.7. Note that double equals is used in the relational test to distinguish it from the assignment operator.

Table 2.7. Conditional Operators

OperationSymbolExample
Equal to==if(a==0) b=b+5;
Not equal to!=if(a != 1) b=b+4;
Greater than&gt;if(a &gt; 2) b=b+3;
Less than&lt;if(a &lt; 3) b=b+2;
Greater than or equal to&gt;=if(a &gt;= 4) b=b+1;
Less than or equal to&lt;=if(a &lt;= 5) b=b+0;

Sometimes, a conditional test needs to combine tests on several values. The tests can be compounded by using logical operators, as follows:

$\begin{array}{l}\text{ANDcondition:} \mathrm{ }\text{if}\left(\left(\text{a}>\text{b}\right)&&\left(\text{c}=\text{d}\right)\right)\text{...}\\ \text{ORcondtion:} \mathrm{ }\text{if}\left(\left(\text{a}>\text{b}\right)||\left(\text{c}=\text{d}\right)\right)\text{...}\end{array}$

URL:

https://www.sciencedirect.com/science/article/pii/B978075068960100002X

## matlab Programming

James C. Squire P.E., Ph.D., Julie Phillips Brown Ph.D., in Programming for Electrical Engineers, 2021

### Relational Expressions

A logical expression is a statement that evaluates to either “true” or “false.” Relational operators are a type of logical operator, and compare two values such as 5>4 (true) or 3≤−4 (false). matlab returns a 1 to indicate true and 0 to indicate false. matlab has several types of relational operators; some of the most common are listed below:

OperatorNameExampleExample result
>Greater than(5>2)1
<Less than7<-60
>=Greater than or equal toa=-5
a >= 6
0
<=Less than or equal toa=7; b=9
a∗b <= a+b
0
==Equal to5 == 51
~=Not equal to5 ∼=50
isequal()Equal to, works with strings, vectors, and matricesa='hello'
b='Hello'
isequal(a,b)
0 (capitalization matters)

Note that one of the most common relational statements, the test to see if two scalar numbers are the same, is not = but rather ==.

In the example below, the function called password() tests to see if the input is “secret” and outputs a 1, if so, and 0, otherwise:

% password tests to see if the input is

% the string 'secret'

result=isequal(input, 'secret');

### Practice Problems

10.

Modify the above function to take a number as an argument and test to see if it is 999. If so, it outputs a 1; otherwise, it outputs a 0. Call the function problem10(). ©

URL:

https://www.sciencedirect.com/science/article/pii/B9780128215029000043

## MATLAB Fundamentals

Brian D. Hahn, Daniel T. Valentine, in Essential MATLAB for Engineers and Scientists (Seventh Edition), 2019

### 2.8.1 The one-line if statement

In the last example MATLAB has to make a decision; it must decide whether or not r is greater than 0.5. The if construct, which is fundamental to all computing languages, is the basis of such decision making. The simplest form of if in a single line is

if condition; statements; end

Note the following points:

condition is usually a logical expression (i.e., it contains a relational operator), which is either true or false. The relational operators are shown in Table 2.4. MATLAB allows you to use an arithmetic expression for condition. If the expression evaluates to 0, it is regarded as false; any other value is true. This is not generally recommended; the if statement is easier to understand (for you or a reader of your code) if condition is a logical expression.

Table 2.4. Relational operators.

Relational operatorMeaning
&lt;less than
&lt;=less than or equal
==equal
~=not equal
&gt;greater than
&gt;=greater than or equal

If condition is true, statement is executed, but if condition is false, nothing happens.

condition may be a vector or a matrix, in which case it is true only if all of its elements are nonzero. A single zero element in a vector or matrix renders it false.

if condition statement, end

Here are more examples of logical expressions involving relational operators, with their meanings in parentheses:

b^2 < 4*a*c $\left({b}^{2}<4ac\right)$

x >= 0 ($x⩾0$)

a ~= 0 ($a\ne 0$)

b^2 == 4*a*c (${b}^{2}=4ac$)

Remember to use the double equal sign (==) when testing for equality:

if x == 0; disp( 'x equals zero'); end

### Exercises

The following statements all assign logical expressions to the variable x. See if you can correctly determine the value of x in each case before checking your answer with MATLAB.

(a) x = 3 > 2

(b) x = 2 > 3

(c) x = -4 <= -3

(d) x = 1 < 1

(e) x = 2 ~= 2

(f) x = 3 == 3

(g) x = 0 < 0.5 < 1

Did you get item (f)? 3 == 3 is a logical expression that is true since 3 is undoubtedly equal to 3. The value 1 (for true) is therefore assigned to x. After executing these commands type the command whos to find that the variable x is in the class of logical variables.

What about (g)? As a mathematical inequality,

$0<0.5<1$

is undoubtedly true from a nonoperational point of view. However, as a MATLAB operational expression, the left-hand < is evaluated first, 0 < 0.5, giving 1 (true). Then the right-hand operation is performed, 1 < 1, giving 0 (false). Makes you think, doesn't it?

URL:

https://www.sciencedirect.com/science/article/pii/B9780081029978000087

## Predefined and Standard Packages

Peter J. Ashenden, in The Designer's Guide to VHDL (Third Edition), 2008

### 9.1 The Predefined Packages standard and env

In previous chapters, we have introduced numerous predefined types and operators. We can use them in our VHDL models without having to write type declarations or subprogram definitions for them. These predefined items all come from a special package called standard, located in a special design library called std. A full listing of the standard package is included for reference in Appendix A.

Because nearly every model we write needs to make use of the contents of this library and package, as well as the library work, VHDL includes an implicit context clause of the form

library std, work; use std.standard.all;

at the beginning of each design unit. Hence we can refer to the simple names of the predefined items without having to resort to their selected names. In the occasional case where we need to distinguish a reference to a predefined operator from an overloaded version, we can use a selected name, for example:

result := std.standard.“<” ( a, b );

### Example 9.1 A comparison operator for signed binary-coded integers

A package that provides signed arithmetic operations on integers represented as bit vectors might include a relational operator, defined as follows:

function “<” ( a, b : bit_vector ) return boolean is

variable tmp1 : bit_vector(a’range) := a;

variable tmp2 : bit_vector(b’range) := b;

begin

tmp1(tmp1‘left) := not tmp1(tmp1‘left);

tmp2(tmp2‘left) := not tmp2(tmp2‘left);

return std.standard.”<” ( tmp1, tmp2 );

end function “<”;

The function negates the sign bit of each operand, then compares the resultant bit vectors using the predefined relational operator from the package standard. The full selected name for the predefined operator is necessary to distinguish it from the function being defined. If the return expression were written as “tmp1 < tmp2”, it would refer to the function in which it occurs, creating a circular definition.

### VHDL-87, -93, and -2002

A number of new operations were added to VHDL in the 2008 revision. They are not available in earlier versions of the language. In summary, the changes are

The types boolean_vector, integer_vector, real_vector, and time_vector are predefined (see Section 4.2.1). The predefined operations on boolean_vector are the same as those defined for bit_vector. The predefined operations on integer_vector include the relational operators (“=”, “/=”, “<”, “>”, “<=”, and “>=”) and the concatenation operator (“&”). The predefined operations on real_vector and time_vector include the equality and inequality operators (“=” and“/=”) and the concatenation operator (“&”).

The array/scalar logic operations and logical reduction operations are predefined for bit_vector and boolean_vector, since they are arrays with bit and boolean elements, respectively.

The matching relational operators “?=”, “?/=”, “?>”, “?>=”, “?<”, and “?<=” are predefined for bit. Further, the operators “?=” and “?/=” are predefined for bit_vector.

The condition operator “??” is predefined for bit.

The operators mod and rem are predefined for time, since it is a physical type.

The maximum and minimum operations are predefined for all of the predefined types.

The functions rising_edge and falling_edge are predefined for bit and boolean. Prior to VHDL-2008, the bit versions of these functions were declared in the package numeric_bit (see Section 9.2.3). However, that was mainly to provide consistency with the std_ulogic versions defined in the std_logic_1164 package. They rightly belong with the definition of the type on which they operate; hence, VHDL-2008 includes them in the package standard. The VHDL-2008 revision of the numeric_bit package redefines the operations there as aliases for the predefined versions. (We discuss aliases in Chapter 11.)

The to_string operations are predefined for all scalar types and for bit_vector. Further, the to_bstring, to_ostring, and to_hstring operations and associated aliases are predefined for bit_vector.

VHDL also provided a second special package, called env, in the std library. The env package includes operations for accessing the simulation environment provided by a simulator. First, there are procedures for controlling the progress of a simulation:

procedure stop (status: integer);

procedure stop;

procedure finish (status: integer);

procedure finish;

When the procedure stop is called, the simulator stops and accepts further input from the user interface (if interactive) or command file (if running in batch mode). When the procedure finish is called, the simulator terminates; simulation cannot continue. The versions of the procedures that have the status parameter use the parameter value in an implementation-defined way. They might, for example, provide the value to a control script so that the script can determine what action to take next.

The env package also defines a function to access the resolution limit for the simulation:

function resolution_limit return delay_length;

We described the resolution limit in Section 2.2.4 when we introduced the predefined type time. One way in which we might use the resolution_limit function is to wait for simulation time to advance by one time step, as follows:

wait for env.resolution_limit;

Since the resolution limit, and hence the minimum time by which simulation advances, can vary from one simulation run to another, we cannot write a literal time value in such a wait statement. The use of the resolution_limit function allows us to write models that adapt to the resolution limit used in each simulation. We need to take care in using this function, however. It might be tempting to compare the return value with a given time unit, for example:

if env.resolution_limit > ns then-- potentially illegal!

-- do coarse-resolution actions

else

-- do fine-resolution actions

end if;

The problem is that we are not allowed to write a time unit smaller than the resolution limit used in a simulation. If this code were simulated with a resolution limit greater than ns, the use of the unit name ns would cause an error; so the code can only succeed if the resolution limit is less than or equal to ns. We can avoid this problem by rewriting the example as:

if env.resolution_limit > 1.0E–9sec then

… -- do coarse-resolution actions

else

… -- do fine-resolution actions

end if;

For resolution limits less than or equal to ns, the test returns false, so the “else” alternative is taken. For resolution limits greater than ns, the time literal 1.0E-9sec is truncated to zero, and so the test returns true. Thus, even though the calculation is not quite what appears, it produces the result we want.

### VHDL-87, -93, and -2002

These versions do not provide the env package. Some tools might provide equivalent functionality through implementation-defined mechanisms.

URL:

https://www.sciencedirect.com/science/article/pii/B9780120887859000095

## Code Shape

Keith D. Cooper, Linda Torczon, in Engineering a Compiler (Second Edition), 2012

### Predicated Execution

Architectures that support predicated execution let the compiler avoid some conditional branches. In iloc, we write a predicated instruction by including a predicate expression before the instruction. To remind the reader of the predicate's purpose, we enclose it in parentheses and follow it with a question mark. For example,

(r17) add ra, rb ⇒ rc

indicates an add operation (ra + rb) that executes if and only if r17 contains true.

### Predicated Execution

an architectural feature in which some operations take a boolean-valued operand that determines whether or not the operation takes effect

The example in Figure 7.9a shows the strength of predicated execution. The code is simple and concise. It generates two predicates, r1 and r2. It uses them to control the code in the then and else parts of the source construct. In Figure 7.9b, predication leads to the same code as the boolean-comparison scheme.

The processor can use predication to avoid executing the operation, or it can execute the operation and use the predicate to avoid assigning the result. As long as the idled operation does not raise an exception, the differences between these two approaches are irrelevant to our discussion. Our examples show the operations required to produce both the predicate and its complement. To avoid the extra computation, a processor could provide comparisons that return two values, both the boolean value and its complement.

### Section Review

The implementation of boolean and relational operators involves more choices than the implementation of arithmetic operators. The compiler writer must choose between a numerical encoding and a positional encoding. The compiler must map those decisions onto the set of operations provided by the target processor's isa.

In practice, compilers choose between numerical and positional encoding based on context. If the code instantiates the value, numerical encoding is necessary. If the value's only use is to determine control flow, positional encoding often produces better results.

### Review Questions

1.

If the compiler assigns the value zero to false, what are the relative merits of each of the following values for true? One? Any non-zero number? A word composed entirely of ones?

2.

How might the treewalk code generation scheme be adapted to generate positional code for boolean and relational expressions? Can you work short-circuit evaluation into your approach?

URL:

https://www.sciencedirect.com/science/article/pii/B9780120884780000074

## Fundamentals of IDL Syntax

LIAM E. GUMLEY, in Practical IDL Programming, 2002

### Finding Values That Meet Selection Critieria

The following example demonstrates how array elements greater than a threshold are found:

The where function returns the indices of the nonzero elements in an array or array expression. Thus, in the previous example, where returned the nonzero indices of the expression (arr gt 35) (recall that relational operators in IDL return 0 for false, and 1 for true). So where returned the locations of arrays elements where the expression (arr gt 35) was true. This is easier to see when the relational operator is separated from the where call:

The array result now contains a value of 1 wherever the expression (arr gt 35) is true in arr. Now where can be called to retrieve the locations of the nonzero elements in result:

The expression passed to where may be as complicated as desired. For example, to find the array values greater than 35 that are also multiples of four:

You should always account for the possibility that where will not find any nonzero values in the input array or expression (i.e., no values meet the prescribed conditions). In this case, where returns a scalar long equal to-1:

For this reason the where function accepts an optional count argument, which returns the number of nonzero elements found:

The optional count argument is recommended whenever where is used within an IDL program.

URL:

https://www.sciencedirect.com/science/article/pii/B9781558607002500033

Top Articles
Latest Posts
Article information

Author: Greg O'Connell

Last Updated: 29/01/2024

Views: 5229

Rating: 4.1 / 5 (42 voted)

Author information

Name: Greg O'Connell

Birthday: 1992-01-10

Address: Suite 517 2436 Jefferey Pass, Shanitaside, UT 27519

Phone: +2614651609714

Job: Education Developer

Hobby: Cooking, Gambling, Pottery, Shooting, Baseball, Singing, Snowboarding

Introduction: My name is Greg O'Connell, I am a delightful, colorful, talented, kind, lively, modern, tender person who loves writing and wants to share my knowledge and understanding with you.