2
votes

I want to have a boolean numpy array fixidx that is the result of comparing numpy arrays a, b, c and d. For example I have the arrays

a = np.array([1, 1])
b = np.array([1, 2])
c = np.array([1, 3])
d = np.array([1, 4])

so the array fixidx has the values

fixidx = [1, 0]

My approach was

fixidx = (a == b) & (b == c) & (c == d)

This works in Matlab but as it turns out Python only puts out a ValueError.

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

any or all won't do the trick or at least I couldn't figure it out.

2
Code works perfectly with no errors. Try ((a == b) & (b == c) & (c == d)).astype(int) to get [1,0].Space Impact

2 Answers

1
votes

Code works perfectly with no errors. Try converting boolean output to integer:

((a == b) & (b == c) & (c == d)).astype(int)
array([1, 0])
1
votes

Let's start by stacking a, b, c and d into a single array x:

In [452]: x = np.stack([a, b, c, d])

In [453]: x
Out[453]: 
array([[1, 1],
       [1, 2],
       [1, 3],
       [1, 4]])

Then you can apply NumPy's unique to each column and test whether the result has one or more elements.

In [454]: fixidx = np.array([np.unique(x[:, i]).size == 1 for i in range(x.shape[1])])

In [455]: fixidx
Out[455]: array([ True, False])

Finally you can cast fixidx to integer if necessary:

In [456]: fixidx.astype(int)
Out[456]: array([1, 0])

Alternatively, you could obtain the same result through NumPy's equal as follows:

fixidx = np.ones(shape=a.shape, dtype=int)
x = [a, b, c, d]
for first, second in zip(x[:-1], x[1:]):
    fixidx *= np.equal(first, second)