Given two matrices
A: m * r
B: n * r
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
.
For example,
A: [[1, 2],
[3, 4]]
B: [[3, 1],
[1, 2]]
gives
C: [[[3, 1], [[1 ,2],
[6, 2]], [2 ,4]],
[9, 3], [[3, 6],
[12,4]], [4, 8]]]
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?
Numpy outer() is the function in the numpy module in the python language. It is used to compute the outer level of products like vectors, arrays, etc. If we try to combine the two vectors of the array's outer level, the numpy outer() function requires more than two levels of arguments that are passed into the function.
Inner and Outer Product. Definition: Inner and Outer Product. If u and v are column vectors with the same size, then uT v is the inner product of u and v; if u and v are column vectors of any size, then uvT is the outer product of u and v.
If the two vectors have dimensions n and m, then their outer product is an n × m matrix.
The Einstein notation expresses this problem nicely
In [85]: np.einsum('ac,bd->abcd',A,B)
Out[85]:
array([[[[ 3, 1],
[ 6, 2]],
[[ 1, 2],
[ 2, 4]]],
[[[ 9, 3],
[12, 4]],
[[ 3, 6],
[ 4, 8]]]])
temp = numpy.multiply.outer(A, B)
C = numpy.swapaxes(temp, 1, 2)
NumPy ufuncs, such as multiply
, have an outer
method that almost does what you want. The following:
temp = numpy.multiply.outer(A, B)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With