Page 1 of 1

Largest eigenvalue (and -vector) of nxn matrix

Posted: Sat Jan 04, 2014 12:15 pm
by Henko

Code: Select all

' Testprogram for function "eigen_n",
' which (tries to) find(s) the largest eigenvector of a matrix
' the "matlib" library is needed
'
option base 1 ! sz=3 ! randomize
graphics ! graphics clear .8,.8,.8 ! draw color 0,0,.6
dim a(sz,sz),ev(sz)
for i=1 to sz ! for j=1 to sz ! read a(i,j) ! next j ! next i
data 1,1,1,1,2,3,-2,1,-3
draw text "largest eigenvalue = " & eigen_n(sz,a,ev) at 10,10
vec_out ("eigenvector",sz,ev,10,40,8,3)
end

' Find largest eigenvalue with eigenvector for nxn matrix,
' using the simplest "power method".
' No results in case of complex or multiple eigenvalues, the
' function will then return a value of 0.
' If the iteration converges, the function returns the eigenvalue
' and the accompanying eigenvector in the vector "ev"
'
def eigen_n (n,mat(,),ev())
dim evo(n)
count=0 ! maxcount=100 ! eps=.00001
labo=1 ! vec_rnd(n,evo,-1,1)
do
  mat_vec(n,n,mat,evo,ev)
  lab=vec_len(n,ev)/vec_len(n,evo)
  dif=abs(abs(lab)-abs(labo)) ! vec_norm(n,ev)
  if dif>eps then 
    labo=lab ! vec_copy(n,ev,evo) ! count=count+1
    end if 
  until dif<eps or count=maxcount
if ev(1)*evo(1)<0 then lab=-lab
if count=maxcount then eigen_n=0 else eigen_n=lab
end def

{/matlib}