numpy 矩阵通过`np.fromfunction` [重复]

5rgfhyps  于 2023-04-21  发布在  其他
关注(0)|答案(1)|浏览(137)

此问题已在此处有答案

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()(10个答案)
Putting lambda in NumPy np.fromfunction() causes TypeError(2个答案)
8天前关闭
当我尝试运行我的代码时,我遇到了这个问题:
ValueError:包含多个元素的数组的真值不明确。使用.any()或.all()
我不知道我应该改变什么和在哪里来解决这个问题。

import numpy as np

n = int(input("Enter the value of n for the nxn matrix: "))

a=np.fromfunction(lambda i, j: n if i==j else (i+1) + (j+1) , (n,n), dtype=int)
print(a)
nx7onnlm

nx7onnlm1#

我想你是假设你的函数被调用了n * n次,每次都有一对新的可能的索引0... n。试着打印这些值来看看发生了什么:

>>> import numpy as np

>>> n = 3
>>> def f(i, j):
...     print(i)
...     print(j)
...     return n if i==j else (i+1) + (j+1)

>>> np.fromfunction(f, (n,n), dtype=int)
[[0 0 0]
 [1 1 1]
 [2 2 2]]
[[0 1 2]
 [0 1 2]
 [0 1 2]]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "...\Python\Python311\site-packages\numpy\core\numeric.py", line 1866, in fromfunction
    return function(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<stdin>", line 4, in f
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

相反,该函数只被调用一次,并使用可能索引的网格!
... if i == j else ...部分中,在比较了ij之后,您将得到一个具有True和False值的布尔数组,因此numpy不确定该怎么做。
相反,对于这种if-else逻辑,依赖于np.where,并且可能使用一点广播来提高效率:

>>> xs, ys = np.indices((n, n), sparse=True)
>>> np.where(np.eye(n), n, xs + ys + 2)
array([[5, 3, 4, 5, 6],
       [3, 5, 5, 6, 7],
       [4, 5, 5, 7, 8],
       [5, 6, 7, 5, 9],
       [6, 7, 8, 9, 5]])

相关问题