Cashel Godfrey
Cashel Godfrey

Reputation: 53

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

When running the following code, I get the Error message "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"

import random
import numpy as np

nx, ny = (32, 32)
xaxis = np.linspace(-310, 310, nx)
yaxis = np.linspace(-310, 310, ny)
xys = np.dstack(np.meshgrid(xaxis, yaxis)).reshape(-1, 2)

oris = random.randint (0, 180)
random_ori=oris

absX = abs(xys[:,0])
absY = abs(xys[:,1])

x_rand=(random.randint (0, 220))
y_rand=(random.randint (0, 220))

width=40
height=80

patch = (x_rand <= absX < x_rand + width) * (y_rand <= absY < y_rand + height)
oris[patch] = random_ori + 30 

The problem seems to be due to the boolean expression:

patch = (x_rand <= absX < x_rand + width) * (y_rand <= absY < y_rand + height)

As the error message suggests, I have tried using .any() and .all(), but the same error message appears.

I can't use np.logical_and or np.logical_or either as I am not working with a numpy array.

Would anyone know why .any() and .all() does not fix the problem, and what I can do to fix it?

Thanks.

Upvotes: 0

Views: 153

Answers (1)

brittAnderson
brittAnderson

Reputation: 1473

I think your problem is that absX has a bunch of numbers and x_rand+width only is one. Your x_rand <= absX returns an array. Apply np.all (or any) to that, and then the test against x_rand + width, e.g. np.all(x_rand <= absX) < x_rand+width.

Upvotes: 1

Related Questions