3
有没有什么办法可以避免使用第二个for
循环进行这样的操作?避免Numpy索引For循环
for x in range(Size_1):
for y in range(Size_2):
k[x,y] = np.sqrt(x+y) - y
或者还有更好的方法来优化吗?现在它对于大尺寸来说非常慢。
有没有什么办法可以避免使用第二个for
循环进行这样的操作?避免Numpy索引For循环
for x in range(Size_1):
for y in range(Size_2):
k[x,y] = np.sqrt(x+y) - y
或者还有更好的方法来优化吗?现在它对于大尺寸来说非常慢。
下面是与broadcasting
一个量化的解决方案 -
X,Y = np.ogrid[:Size_1,:Size_2]
k_out = np.sqrt(X+Y) - Y
益气Divakar的解决方案:如果Y
和X
不是新的范围,但数的某些前载体,使用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
的可能的复制[加快numpy嵌套循环](http://stackoverflow.com/questions/23565573/speed-up-numpy-nested-loop) – pinkfloydx33