I have one 3 x 3 numpy.ndarray
, i.e. H, and one M x N x 3 numpy.ndarray
, i.e. A.
What I want to do is multiplying H with each vector in A.
import numpy as np
H = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]) # 3 x 3 matrix
A = np.array([[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
[[10, 11, 12],
[13, 14, 15],
[16, 17, 18]]]) # 2 x 3 x 3 matrix
For example, in the above code, I want to apply matrix and vector multiplication between H and [1, 2, 3]
, [4, 5, 6]
, ..., [16, 17, 18]
, which are vector elements of A.
Therefore, the result would be
np.array([[[14, 32, 50], # H @ A[0, 0]
[32, 77, 122], # H @ A[0, 1]
[50, 122, 194]], # H @ A[0, 2]
[[68, 167, 266], # H @ A[1, 0]
[86, 212, 338], # H @ A[1, 1]
[104, 257, 410]]] # H @ A[1, 2]
)
When I broadcast H @ A
, H @ A[0]
and H @ A[1]
are applied, which is not that I expected.
Is there a way to broadcast in the way I want?
CodePudding user response:
You could use the @
operator:
A @ H.T
array([[[ 14, 32, 50],
[ 32, 77, 122],
[ 50, 122, 194]],
[[ 68, 167, 266],
[ 86, 212, 338],
[104, 257, 410]]])