1

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?

1
  • 2
    np.einsum('ij, klj -> kli', H, A) Commented Apr 27, 2022 at 8:42

1 Answer 1

4

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]]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.