Logical Operators

Question

How do you do element-wise and and or operations on arrays?

Answer

In IDL, the and and or operators are logical operators which, when applied to an array, operate element-wise on the array and in sequence following standard operator precedence. Thus, in IDL:

IDL> a = [3, 6, 9]
IDL> print, (a gt 4) and (a lt 8)
   0   1   0

In Python, however, and and or are boolean operators and when operated on arrays do not return element-wise comparison but either one of the operands. Thus, if you have the expression x and y, x is returned if x is False and y otherwise; see Martelli (2003, p. 44) for details. Thus, in Python:

>>> import Numeric as N
>>> a = N.array([3, 6, 9])
>>> a > 4
[0,1,1,]
>>> a < 8
[1,1,0,]
>>> (a > 4) and (a < 8)
[1,1,0,]

since a > 4 evaluates as True (because it is non-empty), the and statement returns the result of a < 8 as the final result.

(Note that this issue arises with Numeric arrays but not with numarray arrays. With numarray arrays, an attempt to treat an array like a truth value (e.g. with an and statement) will throw a RuntimeError exception.)

To get element-wise comparison, use the logical_and and logical_or functions in Numeric:

>>> import Numeric as N
>>> a = N.array([3, 6, 9])
>>> N.logical_and(a > 4, a < 8)
[0,1,0,]

Return to the Tips and Examples index page.

Valid HTML 4.01! Valid CSS! Updated: August 18, 2004 by Johnny Lin <email address>. License.