Skip to content Skip to sidebar Skip to footer

Numpy Creation By Fromfunction Error

Code: n=3 x=np.fromfunction(lambda i,j: (i==1)and(j==1), (n,n), dtype=int) leads to 'ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() o

Solution 1:

The documentation is misleading. The function isn't called repeatedly with the indices of each individual cell; it's called once, with index arrays representing the indices of all the cells at once. The return value of this one function call is returned directly:

>>> numpy.fromfunction(lambda *args: 1, (2, 2))
1
>>> numpy.fromfunction(lambda *args: args, (2, 2))
(array([[ 0.,  0.],
       [ 1.,  1.]]), array([[ 0.,  1.],
       [ 0.,  1.]]))

You'll need to change your function to operate that way:

lambda i, j: (i==1) & (j==1)
#                   ^ elementwise bitwise and

Post a Comment for "Numpy Creation By Fromfunction Error"