问题描述
给定两个矩阵
A: m * r
B: n * r
我想生成另一个矩阵C: m * n
,每个条目C_ij
是一个由A_i
的外积计算的矩阵和 B_j
.
I want to generate another matrix C: m * n
, with each entry C_ij
being a matrix calculated by the outer product of A_i
and B_j
.
例如
A: [[1, 2],
[3, 4]]
B: [[3, 1],
[1, 2]]
给予
C: [[[3, 1], [[1 ,2],
[6, 2]], [2 ,4]],
[9, 3], [[3, 6],
[12,4]], [4, 8]]]
我可以使用 for 循环来实现,例如
I can do it using for loops, like
for i in range (A.shape(0)):
for j in range (B.shape(0)):
C_ij = np.outer(A_i, B_j)
我想知道是否有一种矢量化的方式来进行这种计算以加快计算速度?
I wonder If there is a vectorised way of doing this calculation to speed it up?
推荐答案
temp = numpy.multiply.outer(A, B)
C = numpy.swapaxes(temp, 1, 2)
NumPy ufuncs,例如 multiply
,有一个 outer
方法几乎可以满足您的需求.以下:
NumPy ufuncs, such as multiply
, have an outer
method that almost does what you want. The following:
temp = numpy.multiply.outer(A, B)
产生的结果使得 temp[a, b, c, d] == A[a, b] * B[c, d]
.你想要 C[a, b, c, d] == A[a, c] * B[b, d]
.swapaxes
调用重新排列 temp
把它放在你想要的顺序.
produces a result such that temp[a, b, c, d] == A[a, b] * B[c, d]
. You want C[a, b, c, d] == A[a, c] * B[b, d]
. The swapaxes
call rearranges temp
to put it in the order you want.
这篇关于Python - 矩阵外积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!