问题描述
我正在尝试创建一个矩阵,该矩阵的索引(i,j)值对于我正在定义的函数为f(i,j),
.我正在尝试使用numpy.fromfunction
来执行此操作,但无法使其正常工作.这是代码
I'm trying to create a matrix whose value at index (i,j) will be f(i,j),
for a function that I'm defining. I'm trying to do this with numpy.fromfunction
and I haven't been able to get it to work. Here's the code
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)
我收到错误
在fromfunction
的调用中,
我想它必须与np.arange
有关.
in the call to fromfunction
and I suppose it must have to do with np.arange
.
最初,我有range(1,j+2)
,但是随后出现错误
Originally, I had range(1,j+2)
but then I got the error
能告诉我我需要做什么吗?
Can you tell me what I need to do, please?
推荐答案
我认为您必须先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
并非一次就传递坐标,而是一次传递:
Indeed, fromfunction
passes the coordinates not one-by-one but in one go:
>>> 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
这篇关于如何在numpy.fromfunction内使用范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!