简体   繁体   中英

large matrix diagonalization python

I am using the linalg in scipy to get the egenvalues and eigenvectors of a 155X156 matrix. However, the order of the eigenvalues seems to be random compared with the matrix. I want the first eigenvalues to correspond to the first number in the matrix. Please see bellow my routine. I am first reading a file that contains all the float numbers like this (the 1_1o.dat)

 2533297.650278 -2373859.531153      
 37695.845843     425449.129032

then I read them as an array

  [2533297.650278, -2373859.531153,      37695.845843,     425449.129032...]

and then reshape to a 156X156 matrix. I want all the eigenvalues and the corresponding eigenvectors to be printed in the order the matrix is read. I know that in the end my eigenvalues (156 numbers) should be listed from the small number to the higher, not randomly as the current routine does. And of course the same order for corresponding eigenvectors. Could anyone help me with this?

Thanks.

from scipy import linalg
from scipy.linalg import *
file2 = open('1_1f.dat', 'w')                                   
with open('1_1o.dat', 'rU') as file:                            
    File = file.readlines()                                     
    nums2 = np.array(File)                                         
    nums2 = [float(i.rstrip('\n')) for i in nums2[0].split()]  
    nums2 = np.reshape(nums2, (156, 156))
    print eig(nums2)    
    print >> file2, eig(nums2)                         
    file2.close()   

According to the documentation of np.linalg.eig part: Returns, w: (...,M) array:

The eigenvalues, each repeated according to its multiplicity. The eigenvalues are not necessarily ordered . The resulting array will be always be of complex type. When a is real the resulting eigenvalues will be real (0 imaginary part) or occur in conjugate pairs

How to sort the values is shown here and copied for completeness:

import numpy as np
A = np.array([[3,1,-1], [1,3,-1], [-1,-1,5]])
w,v =  np.linalg.eig(A)
print w
idx = w.argsort()[::-1] #large to small
# idx = w.argsort() #small to large
w = w[idx]
v = v[:,idx]
print w # now they are ordered and you can iterate through your results to write them to your file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM