4
如何矢量化以下双循环?此Numpy双循环的矢量化
我有一个N乘A矩阵和一个N乘B矩阵,其中A和B可能不同,N比A和B小得多。我想要如下生成A乘B矩阵,但理想情况下没有循环:
import numpy as np
def foo(arr):
# can be anything - just an example so that the code runs
return np.sum(arr)
num_a = 12
num_b = 8
num_dimensions = 3
a = np.random.rand(num_dimensions, num_a)
b = np.random.rand(num_dimensions, num_b)
# this is the loop I want to eliminate:
output = np.zeros((num_a, num_b))
for i in xrange(num_a):
for j in xrange(num_b):
output[i,j] = foo(a[:,i] - b[:,j])
任何想法?
谢谢,我知道从中学到很多东西。另外令人难以置信的矢量化版本对我的完整问题要快多少。前231秒,后2秒! – YXD