首页 > 解决方案 > 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?

标签: pythonnumpyfor-loopoptimizationnumpy-ndarray

解决方案


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])


推荐阅读