Agape Gal'lo - 9 months ago 59

Python Question

I need to multiply matrices of different shapes, M and N with a finite size of MxN.

I think an example will make it more clear:

A (shape: 4x4) =

`0 3 0 0`

0 0 4 0

0 0 0 3

0 0 0 0

B (shape: 7x7) =

`3 0 0 0 0 0 0`

0 2 0 0 0 0 0

0 0 1 0 0 0 0

0 0 0 0 0 0 0

0 0 0 0 -1 0 0

0 0 0 0 0 -2 0

0 0 0 0 0 0 -3

As a result, I want a matrix of shape (4*7 x 4*7) which means (28 x 28) as follows:

`0 3*B 0 0`

0 0 4*B 0

0 0 0 3*B

0 0 0 0

where B is still our matrix of shape (7x7) and the 0 represents a block of all zeroes measuring (7x7).

Maybe there is a function with numpy which can do that... but I can't find it.

(just for information, that's for Quantum mechanics)

Answer

You're looking for the Kronecker product, np.kron, which is convenient to make block matrices like this:

```
>>> A = np.array([[1, 2], [0, 1]])
>>> B = np.array([[1, 2, 3], [0, 1, 3], [0,0,0]])
>>> np.kron(A,B)
array([[1, 2, 3, 2, 4, 6],
[0, 1, 3, 0, 2, 6],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 2, 3],
[0, 0, 0, 0, 1, 3],
[0, 0, 0, 0, 0, 0]])
```