3

Is there any way to avoid using a second for loop for an operation like this?

for x in range(Size_1):
    for y in range(Size_2):
        k[x,y] = np.sqrt(x+y) - y

Or is there a better way to optimize this? Right now it is incredibly slow for large sizes.

1

2 Answers 2

2

Here's a vectorized solution with broadcasting -

X,Y = np.ogrid[:Size_1,:Size_2]
k_out = np.sqrt(X+Y) - Y
Sign up to request clarification or add additional context in comments.

Comments

0

Supplementing Divakar's solution: If Y and X are not new ranges but some preexisting vectors of numbers, use np.ix_:

Y, X = np.array([[1.3, 3.5, 2], [2.0, -1, 1]])
Y, X = np.ix_(Y, X) # does the same as Y = Y[:, None]; X = X[None, :]
out = np.sqrt(Y+X) - X

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.