【发布时间】:2011-11-28 17:35:45
【问题描述】:
如何向量化以下双循环?
我有一个 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])
有什么想法吗?
【问题讨论】:
标签: python numpy linear-algebra