fact
fact

Reputation: 557

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.

Upvotes: 5

Views: 2459

Answers (2)

yevgeniy
yevgeniy

Reputation: 908

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)

Upvotes: 0

Alex Riley
Alex Riley

Reputation: 176770

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.

Upvotes: 7

Related Questions