How do you get Matlab-like vectorization when using NumPy? The key is using parentheses when using logical operators. Here’s an example:
from numpy import *
a = array([1,2,3,4,5])
b = array([5,4,3,2,1])
c = array([1,2,2,2,1])
# ===The right way===
(a<5) & (b>3) & (c==2)
# array([ False, True, False, False, False], dtype=bool)
# ===The wrong way===
a<5 & b>3 & c==2
# ValueError:
# The truth value of an array with more than
# one element is ambiguous. Use a.any() or a.all()
Alternatively, use NumPy’s logical_and and logical_or functions . . . but these functions only take two arguments at a time.
Tags: array, boolean, indexing, logical operators, vectorization