简体   繁体   中英

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

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.

Colin's answer is great. Let me just add that there is also the package Arpack.jl which provides bindings to the ARPACK Fortran library. The exported method eigs also has an option nev to specify the number of requested eigenvalues/vectors.

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