我试图创建一个矩阵,其索引(i,j)的值对于我定义的函数将为f(i,j),
。我试图用numpy.fromfunction
来做这件事,但我还没有能够让它发挥作用。这是代码
import numpy as np
def f(i,j):
return sum((i+1)//k for k in np.arange(1,j+2))
def M(N):
shape = np.array([N,N])
np.fromfunction(f, shape,dtype = np.int)
A= M(5)
我收到错误
builtins.TypeError:只有length-1数组可以转换为Python标量
致fromfunction
,我想这必须与np.arange
有关。
最初,我有range(1,j+2)
,但后来我收到了错误
TypeError:只能将整数标量数组转换为标量索引
你能告诉我我需要做什么吗?
答案 0 :(得分:2)
我认为你必须先vectorize
f
:
>>> np.fromfunction(np.vectorize(f), (5, 5), dtype=int)
array([[ 1, 1, 1, 1, 1],
[ 2, 3, 3, 3, 3],
[ 3, 4, 5, 5, 5],
[ 4, 6, 7, 8, 8],
[ 5, 7, 8, 9, 10]])
确实,fromfunction
不是一个接一个地传递坐标,而是一次性传递坐标:
>>> def f(i, j):
... print(i, j)
... return sum((i+1)//k for k in range(1, j+2))
...
>>> np.fromfunction(f, (5, 5), dtype=int)
[[0 0 0 0 0]
[1 1 1 1 1]
[2 2 2 2 2]
[3 3 3 3 3]
[4 4 4 4 4]] [[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/paul/local/lib/python3.6/site-packages/numpy/core/numeric.py", line 1914, in fromfunction
return function(*args, **kwargs)
File "<stdin>", line 3, in f
TypeError: only integer scalar arrays can be converted to a scalar index