python - numpy.fromfunction with specified non-arange-like array
问题描述
I have defined a function;
def f(x,y):
return (1+x)**3.2 * np.cos(y**2.31+x)
and have the following two arrays:
x = np.linspace(10,20,10)
y = np.linspace(5,8,5)
Now I wish to create a 10 x 5 matrix where each (i,j) element is given by f(x[i],x[j])
.
This is easily achieved with a for loop:
result = np.zeros(len(x)*len(y)).reshape((len(x),len(y)))
for i in range(len(x)):
for j in range(len(y)):
result[i][j] = f(x[i],y[j])
However, I want to significantly increase computation time so I am looking for a non-for loop approach.
It would seem that np.fromfunction
brings me partly there:
result = np.fromfunction(lambda x, y: f(x,y), (10, 5), dtype=int)
However, this takes x and y to be arange-like, i.e. this takes elements x = 0,1,...,9 and y = 0,1,...,4.
Is there a way to tell this function that I want it to take my previously defined arrays for x and y.
If this is not possible with np.fromfunction
, is there another way to achieve the same result I get with my for loop, but with less computation time?
解决方案
you can use:
np.fromfunction(lambda i, j: f(x[i],y[j]), (len(x),len(y)), dtype=int)
you have to specify dtype=int
otherwise the data-type of the coordinate will be float
which can not be used as indices in f(x[i],y[j])
推荐阅读
- python - Azure Functions 可以用 Python 编写吗?
- javascript - 是否有理由括号运算符 [] 可能无法在反应组件中与 getElementsByClassName() 一起使用?
- c# - 导航下一页时水晶报表查看器提示数据库登录失败
- c# - SQL查询结果到数组
- python - 在这种情况下,我应该在整个程序中保留池对象(及其工作人员)吗?
- javascript - 使构造函数在 js 文件中可用
- vue.js - 你如何在 web 组件中包含 vuetify
- python - 如何分配第一场比赛和第二场比赛?
- android - 我的单例可以被多次调用
- javascript - 在客户端动态汇总从每日到每周的指标