Search code examples
juliaeigenvalueeigenvector

Get eigenvectors corresponding to the p largest eigenvalues in Julia


I looked at eigvecs and eigen but they both do not order the eigenvectors by the magnitude of eigenvalues. Is this something that we have to code ourself?

testM=diagm(0=>[1,3,2])
eigvals(testM)
eigvecs(testM)
U=eigen(testM)
U.vectors
U.values

Solution

  • The old answer was use eigfact. However, from v1.0, this has been renamed to eigen and moved to the standard library package LinearAlgebra, so you'll need a using LinearAlgebra at the top of your code. Once you've done this, you can see the docs for eigen using ?eigen. Note, I've also updated this answer to replace flipdim with reverse (another v1.0 change).

    For symmetric input, you can optionally pass in a UnitRange{Int} to get the eigenvectors corresponding to the k smallest or largest eigenvalues:

    ef = eigen(Symmetric(x), 1:k)   #k smallest eigenvalues/vectors
    ef.values
    ef.vectors
    

    or

    K = size(x, 1)
    ef = eigen(Symmetric(x), K-k+1:K) #k largest eigenvalues/vectors
    ef.values
    ef.vectors
    reverse(ef.values, dims=1)    #If you want ordered largest to smallest
    reverse(ef.vectors, dims=2)   #If you want ordered largest to smallest
    

    For non-symmetric input, you need to compute all eigenvalues/vectors and then take whatever slice you want. The output is still sorted, so:

    K = size(x, 1)
    ef = eigen(x)
    ef.values[1:k]           #smallest k
    ef.vectors[:, 1:k]       #smallest k
    ef.values[K-k+1:K]       #largest k
    ef.vectors[:, K-k+1:K]   #largest k
    

    As before, use reverse if you want the largest k ordered largest to smallest.