Search code examples
pythonnumpymatrix-multiplicationkronecker-product

In numpy, multipy two structured matrices concisely


I have two matrices. The first has the following structure:

[[1, 0, a],
 [0, 1, b],
 [1, 0, c],
 [0, 1, d]]

where 1, 0, a, b, c, and d are scalars. The matrix is 4 by 3

The second is just a 2 by 3 matrix:

[[r1],
[r2]]

where r1 and r2 are the first and second rows respectively, each having 3 elements. I would like the output to be:

[[r1, 0, a*r1],
 [0, r1, b*r1],
 [r2, 0, c*r2],
 [0, r2, d*r2]]

which would be a 4 by 9 matrix. This is similar to the Kronecker product, except separately for each row of the second matrix. Of course this could be done with cumbersome loops which I want to avoid. How can I do this concisely?


Solution

  • Using broadcasting, with x.shape (n, 3), and y.shape (n//2, 3):

    out = (x.reshape(-1, 2, 3, 1) * y.reshape(-1, 1, 1, 3)).reshape(-1, 9)