简体   繁体   中英

Fastest way to initialize numpy array with values given by function

I am mainly interested in ((d1,d2)) numpy arrays (matrices) but the question makes sense for arrays with more axes. I have function f(i,j) and I'd like to initialize an array by some operation of this function

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

This is readable and works but I am wondering if there is a faster way since my array A will be very large and I have to optimize this bit.

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 so should be quite a bit faster than Python for loops for larger arrays.

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

Note that if your arrays are of different size, then you have to create a meshgrid:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM