2016-07-19 83 views
1

我有两个数组x.dim = (N,4)y.dim = (M, M, 2)和函数f(a, b),它们分别将KL维向量作为参数。我想获得一个数组res.dim = (N, M, M)这样向量化三个嵌套循环 - NumPy

for n in range(N): 
    for i in range(M): 
    for j in range(M): 
     res[n, i, j] = f(x[n], y[i, j]) 

无法获取如何在这种情况下使用apply。预先感谢您的帮助!

def f(a, b): 
    return max(0, 1 - np.sum(np.square(np.divide(np.subtract(b, a[0:2]), a[2:4])))) 
+0

这可不行,'I,J在范围(N)'? int对象是不可迭代的?假设范围(N)是从0到N-1的整数列表 –

+0

那么你写它如何在实践中:) –

回答

1

这里有一个量化的使用NumPy broadcasting和切片上市功能的工作方式 -

# Slice out relevant cols from x 
x_slice1 = x[:,None,None,:2] 
x_slice2 = x[:,None,None,2:4] 

# Perform operations using those slices to correspond to iterative operations 
out = np.maximum(0,1-(np.divide(y-x_slice1,x_slice2)**2).sum(3))