Fastest way to initialize numpy array with values โ€‹โ€‹given by function

I'm mainly interested in ((d1, d2)) numpy arrays (matrices), but the question makes sense for arrays with a lot of axes. I have a function f (i, j) and I would like to initialize an array with some work of this function

A=np.empty((d1,d2))
for i in range(d1):
    for j in range(d2):
        A[i,j]=f(i,j)

      

It's readable and works, but I'm wondering if there is a faster way since my array A will be very large and I need to optimize that bit.

+3


source to share


2 answers


One way is to use np.fromfunction

. Your code can be replaced with the line:

np.fromfunction(f, shape=(d1, d2))

      



This is implemented in terms of NumPy functions and should therefore be quite a bit faster than Python loops for

for large arrays.

+5


source


a=np.arange(d1)
b=np.arange(d2)
A=f(a,b)

      

Note that if your arrays are of different sizes, you need to create a meshgrid:



X,Y=meshgrid(a,b)
A=f(X,Y)

      

0


source







All Articles