Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid Numpy Index For loop

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.

like image 721
John Avatar asked Apr 21 '26 03:04

John


1 Answers

Here's a vectorized solution with broadcasting -

X,Y = np.ogrid[:Size_1,:Size_2]
k_out = np.sqrt(X+Y) - Y
like image 66
Divakar Avatar answered Apr 24 '26 00:04

Divakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!