Search code examples
pythonmatrixmodulepython-module

create module in python for diagonalizing matrix


For example I have a Hermitian matrix, A and I Diagonalize it with matrix B as:

A11= -0.0034
A12=  -0.007 -1j*0.0098 
A13=  -0.0112 - 1j*0.0712 
A21= A12.conjugate()
A22=  0.2162
A23=  1.062 - 1j*0.0584
A31= A13.conjugate()
A32= A23.conjugate()
A33=  2.462

A= matrix([[A11,A12,A13],[A21,A22,A23],[A31,A32,A33]])

eigenvalues_of_A, eigenvectors_of_A = numpy.linalg.eig(A);
B = eigenvectors_of_A[:,abs(eigenvalues_of_A).argsort()]          

diagonal_matrix= B.I * A * B

Which is straight forward.

What I want is to create a module. Lets say I will input 100 different Hermitian matrices and import the module in an existing python script to compute the 100 different B matrices (for each of the different inputs).

EDIT (making my question more general)

Reason: The reason for creating the module is to use it in more general purpose. By general I mean, lets say in a single python script, I have different types of matrices (for example, Hermitian matrix, real matrix, general complex matrix); now diagonalization of different types of matrices are different. so I want to create a module (which contains different diagonalization procedures depending on the type of the matrix) and call it whenever I need to diagonalize any matrix.

Confession: I have no idea how to create a module.


Solution

  • What you can do is use a dictionary to store 100 input Hermitian matrices using a for loop as:

    input_dict={}
    for i in range(100):
        new_A = matrix([[A11,A12,A13],[A21,A22,A23],[A31,A32,A33]]) # new input matrix (A)
        input_dict[i] = new_A
    

    After that use another dictionary to store 100 B matrices as:

    B_matrices={}
    for i in input_dict.keys():
        eigenvalues_of_A, eigenvectors_of_A = numpy.linalg.eig(input_dict[i]);
        B = eigenvectors_of_A[:,abs(eigenvalues_of_A).argsort()]          
        B_matrices[i] = B 
    

    Now, input_matrix[i] gives you ith input matrix and B_matrices[i] gives you corresponding B matrix.

    You can create a module for diagonal matrix as:

    def diagonalize(A):
        eigenvalues_of_A, eigenvectors_of_A = numpy.linalg.eig(A);
        B = eigenvectors_of_A[:,abs(eigenvalues_of_A).argsort()]         
        diagonal_matrix= B.I * A * B
        return diagonal_matrix
    

    Now call it as:

    diagonal_matrix = diagonalize(A)