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.

user
  • 5,370
  • 8
  • 47
  • 75
John
  • 33
  • 2
  • Possible duplicate of [Speed up numpy nested loop](http://stackoverflow.com/questions/23565573/speed-up-numpy-nested-loop) – pinkfloydx33 Feb 09 '17 at 20:17

2 Answers2

2

Here's a vectorized solution with broadcasting -

X,Y = np.ogrid[:Size_1,:Size_2]
k_out = np.sqrt(X+Y) - Y
Divakar
  • 218,885
  • 19
  • 262
  • 358
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
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99