Is there a function to sort eigenvectors in by decreasing eigenvalues

Having computed eigenvectors and eigenvalues of a matrix with pytorch,
w, lamb = torch.eig(matrix,eigenvectors=True)

Is there a function to sort the eigenvectors in the decreasing order of the eigenvalues?

You can use .sort() on the eigenvalues and use the indices to get the same sorting in the eigenvectors.

@albanD, is the following right? Especially the dim?

sortedEig, indices=torch.sort(w, dim=0, descending=True, out=None)
lambSort = lamb.gather(dim=1, index=indices)


You don’t need to specify out=None.

This looks good according to the doc yes.

Thanks for your help, lambSort is a N x 2 tensor instead of N x N tensor which lamb actually is. How do I fix this?

Ho sorry I misread, I think you want index_select() instead of gather here.

OK! Since the first element/column of the eigenvalue tensor is the real part and the second element is the imaginary part, is it safe to use/take just the first element(real part) for sorting? Or do I need to combine them? If yes, is there a way to combine them?

If yes, is there a way to combine them?

That depends on your application ! Do you want to only consider the real part? Or the norm of the complex number?

I am actually implementing PCA so I guess I dabble ignore the complex elements.