5

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.

1

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.