My matrix:
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
I want c
as:
np.array([[5, 10, 6, 12], [15, 20, 18, 24]])
Entry wise multiplication of a
by b
, then concatenate them. How to do this effectively without double loops?
What you are looking for is the Kronecker product. In Numpy, you can get it via numpy.kron()
:
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([5, 6]) # May also be 2D, as in the question
c = np.kron(b, a)
print(c)
# >>> [[ 5 10 6 12]
# [15 20 18 24]]
The order of arguments in kron()
matters here: writing kron(a, b)
would produce the same values in c
, but in different order, namely [[5, 6, 10, 12], [15, 18, 20, 24]]
.