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?
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?
You can use broadcasting and a transpose:
>>> a
array([[1, 2],
[3, 4]])
>>> b
array([[5, 6]])
>>> (a[..., None] * b)
array([[[ 5, 6],
[10, 12]],
[[15, 18],
[20, 24]]])
Then with the transpose:
>>> (a[..., None] * b).transpose((0,2,1))
array([[[ 5, 10],
[ 6, 12]],
[[15, 20],
[18, 24]]])
Finally, a reshape:
>>> (a[..., None] * b).transpose((0,2,1)).reshape(2, -1)
array([[ 5, 10, 6, 12],
[15, 20, 18, 24]])
Perhaps, it's cleaner with np.swapaxes
:
>>> np.swapaxes((a[..., None] * b), 1, 2).reshape(2, -1)
array([[ 5, 10, 6, 12],
[15, 20, 18, 24]])
What you are looking for is the Kronecker product. In Numpy, you can get it via
numpy.kron()
:The order of arguments in
kron()
matters here: writingkron(a, b)
would produce the same values inc
, but in different order, namely[[5, 6, 10, 12], [15, 18, 20, 24]]
.