python - Simple Numpy 2-D matrix and meshgrid - ValueError: The truth value of an array with more than one element is ambiguous -
i'm new python, , task simple, i'm not getting it. i'm trying model light transmission through 2-d aperture using grid: if light transmitted, grid-element 1; if not, 0.
i'm having trouble when iterating through 2-d matrix. think there issue when comparing element of numpy array scalar value, because 2 conditions must met. tried a.any() , a.all(), &, , np.logical_and(), can't seem them work.
def make_object(x,y,a,b): f = np.zeros((len(x),len(y))) if np.abs(x) < (a/2.0): if np.abs(y) < (b/2.0): f[x][y] = 1.0 return f = 6.0 # width of slit b = 6.0 # height of slit n = 20.0 x = np.linspace(-10.0,10.0,n) y = np.linspace(-10.0,10.0,n) x,y = np.meshgrid(x,y) z = make_object(x,y,a,b) print z i error message:
--------------------------------------------------------------------------- valueerror traceback (most recent call last) <ipython-input-13-fef282d4a308> in <module>() 29 x,y = np.meshgrid(x,y) 30 ---> 31 z = make_object(x,y,a,b) 32 33 <ipython-input-13-fef282d4a308> in make_object(x, y, a, b) 8 f = np.zeros((len(x),len(y))) 9 ---> 10 if np.abs(x) < (a/2.0): 11 if np.abs(y) < (b/2.0): 12 f[x][y] = 1.0 valueerror: truth value of array more 1 element ambiguous. use a.any() or a.all() any ideas i'm doing wrong?
edit: code used without vectorization
for i, xi in enumerate(x): j, yj in enumerate(y): if np.abs(xi) < a/2: if np.abs(yj) < b/2: f[i][j] = 1.0
the problem x , y arrays, not individual elements. heres code evaluates before reaches error:
if array([true, false, ... ]): to python, evaluating whether entire array true or false makes no sense. if want use if statements, have iterate through array , check if individual elements less cutoff rather entire arrays.
for in range(f.shape[0]): j in range(f.shape[1]): if x[i][j] < a/2: if y[i][j] < b/2: f[i][j] = 1 however, since using numpy, not need if statements , can take advantage of vectorization , solve problem in single line.
f[ np.logical_and(np.abs(x) < a/2.0, np.abs(y) < b/2.0) ] = 1
Comments
Post a Comment