2

I have a for-loop with generates random Hermitian matrices using a function, diagonalizes it and stores the eigenvalues. However, for some of the instances the diagonalization fails to converge and the code stops.

I want that, if the diagonalization fails, it should skip to the next instance. As a pseudo code:

vals_list = []
for i in range(1000):
    M = random_matrix(....) #generates a 2D numpy array
    vals,vecs = np.linalg.eigh(M)
    vals_list.append(vals)

How to modify this to have skip the instances when the diagonalization does not converge?

lovespeed
  • 4,835
  • 15
  • 41
  • 54
  • That means something is not right with your Hermitian matrix. Can you provide one of those instances? – percusse Feb 15 '16 at 09:39
  • @percusse I force the matrices to be Hermitian by doing `H=H+H.T.conj()`. Actually, the failing of the diagonalization for some instances is alright because of degeneracy issues. – lovespeed Feb 15 '16 at 09:43
  • Degenerecy does not relate to eigenvalues. They just come out as numbers close to zero with some numerical noise. You seem to conjugate twice. – percusse Feb 15 '16 at 09:44
  • I am sure that there is no problem with the matrices. I know that the function `random_matrix` returns a Hermitian matrix. And by degeneracy I mean, when there are many eigenvalues very close to each other the diagonalization routine can fail, that is what is happening here. I just need to skip those instances. – lovespeed Feb 15 '16 at 09:54
  • 2
    I'm also pretty sure that cannot happen that often with random matrices but anyways you can put your code under `try:` and use `except LinAlgErr:` to do what you would like to have instead (or simply `pass`) – percusse Feb 15 '16 at 09:56

0 Answers0