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 to share