I need to multiply a matrix, e.g. a numpy array A with dimensions[3x2] by a 1d array B, of dimensions [1x4] to produce an array C of 4 [3x2] matrices, i.e. [4 x [3x2] ]
So for example C[0] would be a [3x2] matrix = A*B[0]
C[1] = A*B[1]
etc.
without a for i in B loop, but as a 1 line operation.
CodePudding user response:
Use broadcasting:
>>> a = np.arange(6).reshape(3, 2)
>>> a
array([[0, 1],
[2, 3],
[4, 5]])
>>> b = np.arange(4).reshape(1, 4)
>>> b
array([[0, 1, 2, 3]])
>>> c = b[None].T * a # Multiply (4, 1, 1) with (3, 2)
>>> c
array([[[ 0, 0],
[ 0, 0],
[ 0, 0]],
[[ 0, 1],
[ 2, 3],
[ 4, 5]],
[[ 0, 2],
[ 4, 6],
[ 8, 10]],
[[ 0, 3],
[ 6, 9],
[12, 15]]])
>>> c.shape
(4, 3, 2)