Python - Matrix External Product

For two matrices

A: m * r B: n * r 

I want to generate another matrix C: m * n , and each entry C_ij is a matrix calculated by the external 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 this 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 vectorized way to do this calculation to speed it up?

+8
python numpy matrix
source share
3 answers
 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. Following:

 temp = numpy.multiply.outer(A, B) 

gives such a result 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 translates temp to place it in the order you want.

+6
source share

Einstein's designation describes this problem well

 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]]]]) 
+13
source share

Use numpy ;

 In [1]: import numpy as np In [2]: A = np.array([[1, 2], [3, 4]]) In [3]: B = np.array([[3, 1], [1, 2]]) In [4]: C = np.outer(A, B) In [5]: C Out[5]: array([[ 3, 1, 1, 2], [ 6, 2, 2, 4], [ 9, 3, 3, 6], [12, 4, 4, 8]]) 

After you get the desired result, you can use numpy.reshape() to form it in almost any form,

 In [6]: C.reshape([4,2,2]) Out[6]: array([[[ 3, 1], [ 1, 2]], [[ 6, 2], [ 2, 4]], [[ 9, 3], [ 3, 6]], [[12, 4], [ 4, 8]]]) 
0
source share

All Articles