How to multiply array by each element of second array and concatenate them?

119 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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]].

0
On

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]])