Search code examples
pythonfor-loopif-statementmatrix-multiplicationkronecker-product

Kronecker Product in a Loop


I am new in learning Python. I want to calculate λ_i , ρ_i matrices as the attached image, while n=3, i=1:n.

Definitions of λ_i , ρ_i

My initial Code is:

n=3
σ_0 = np.eye(2)
σ_1 = np.array([[1, 0 ],[0, -1]])
σ_2 = np.array([[0, -1],[1, 0]])
σ = np.array([σ_0 , σ_1 , σ_2])

But I don't know how to calculate the Kronecker product iteratively in a loop. Can you please help me how to write a loop for introducing these matrices in aloop.


Solution

  • You can use np.kron for the Kronecker product. For the iteration, you can use a for-loop or the reduce function.

    import numpy as np
    from functools import reduce
    
    def lambda_(s0, s1, s2, i, n):
        if i > 1:
            first = reduce(np.kron, [s1]*(i-1))
        else:
            first = 1
    
        if (n-i) > 0:
            last = reduce(np.kron, [s0]*(n-i))
        else:
            last = 1
        return np.kron( np.kron(first, s2), last)
    
    def rho_(s0, s1, s2, i, n):
        if i > 1:
            first = reduce(np.kron, [s0]*(i-1))
        else:
            first = 1
    
        if (n-i) > 0:
            last = reduce(np.kron, [s1]*(n-i))
        else:
            last = 1
        return np.kron( np.kron(first, s2), last)
    
    lambda_vals = {
        i: lambda_(σ_0, σ_1, σ_2, i, n=3)
        for i in range(1, 3+1)
    }
    

    The lambda_vals is a dictionary with each value of i as the keys and the resulting lambda calculations as the values.

    {
     1: array([[ 0,  0,  0,  0, -1,  0,  0,  0],
            [ 0,  0,  0,  0,  0, -1,  0,  0],
            [ 0,  0,  0,  0,  0,  0, -1,  0],
            [ 0,  0,  0,  0,  0,  0,  0, -1],
            [ 1,  0,  0,  0,  0,  0,  0,  0],
            [ 0,  1,  0,  0,  0,  0,  0,  0],
            [ 0,  0,  1,  0,  0,  0,  0,  0],
            [ 0,  0,  0,  1,  0,  0,  0,  0]]),
     2: array([[ 0,  0, -1,  0,  0,  0,  0,  0],
            [ 0,  0,  0, -1,  0,  0,  0,  0],
            [ 1,  0,  0,  0,  0,  0,  0,  0],
            [ 0,  1,  0,  0,  0,  0,  0,  0],
            [ 0,  0,  0,  0,  0,  0,  1,  0],
            [ 0,  0,  0,  0,  0,  0,  0,  1],
            [ 0,  0,  0,  0, -1,  0,  0,  0],
            [ 0,  0,  0,  0,  0, -1,  0,  0]]),
     3: array([[ 0, -1,  0,  0,  0,  0,  0,  0],
            [ 1,  0,  0,  0,  0,  0,  0,  0],
            [ 0,  0,  0,  1,  0,  0,  0,  0],
            [ 0,  0, -1,  0,  0,  0,  0,  0],
            [ 0,  0,  0,  0,  0,  1,  0,  0],
            [ 0,  0,  0,  0, -1,  0,  0,  0],
            [ 0,  0,  0,  0,  0,  0,  0, -1],
            [ 0,  0,  0,  0,  0,  0,  1,  0]])
    }