Suppose that we have 2 2X2 numpy arrays:
X=np.array([[0,1],[1,0]])
and
I=np.array([[1,0],[0,1]])
Consider the Kronecker product
XX=X^X
where I have let the symbol ^
be the symbol for Kronecker product. This can easily be computed via the numpy.kron()
function in python:
import numpy as np
kronecker_product = np.kron(X, X)
Now, suppose that we want to compute
XX=I^X^X
numpy.kron()
only takes two arrays as arguments and expects them to be the same dimension. How can I perform this operation using numpy.kron()
or other technique in python?
CodePudding user response:
As with anything like this, try:
XX = np.kron(I, np.kron(X, X))
Output:
>>> XX
array([[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0]])
You can nest calls to kron
any number of times. For example, for XX = A^B^C^D^E
, use
XX = np.kron(A, np.kron(B, np.kron(C, np.kron(D, E))))
If you don't like the verbosity there, you could create an alias for np.kron
:
k = np.kron
XX = k(A, k(B, k(C, k(D, E))))
Or, better yet, use reduce
from the Python built-in module functools
to do it in an even more readable fashion:
import functools as ft
lst = [A, B, C, D, E]
XX = ft.reduce(lambda x, y: np.kron(x, y), lst)
Note: I tested all of this and it works perfectly.