Code: Select all
' eigenvalue function for 2x2 matrices
' main program is used to test the function
' the function "eigen_2" should be added to the "matlib" library
' if you use that library (program section of SB forum)
' function to find largest eigenvalue of nxn matrix coming soon
'
option base 1
graphics ! graphics clear .8,.8,.8 ! draw color 0,0,.6
dim a(2,2),ev(2,2),lab(2)
read a(1,1),a(1,2),a(2,1),a(2,2) ! data 1,2,3,4
if eigen_2(a,ev,lab) then
vec_out ("eigenvalues",2,lab,10,10,8,3)
' 1st column in the vector output is the element number
' the actual eigenvalues are in the 2nd column
mat_out ("eigenvectors",2,2,ev,10,150,8,3)
else
draw text "no results" at 10,50
end if
end
' eigenvalues and eigenvectors of a 2x2 matrix
' matrix has real coefficients
' matrix is passed as "a"
' function returns 0 if no real eigenvalues are found,
' else the function returns 1
' 2 eigenvalues are returned in the vector "lab"
' 2 eigenvectors are returned as colums in the matrix "ev"
' eigenvectors are normalized to a length of 1
' library "matlib" is needed
'
def eigen_2 (a(,),ev(,),lab())
dim x(2)
eigen_2=0
discr=(a(1,1)-a(2,2))^2+4*a(1,2)*a(2,1)
if discr<0 then return
eigen_2=1
discr=sqrt(discr) ! s=a(1,1)+a(2,2)
lab(1)=(s+discr)/2 ! lab(2)=(s-discr)/2
for j=1 to 2
x(1)=1
if a(1,2) then
x(2)=(lab(j)-a(1,1))/a(1,2)
else
x(2)=(lab(j)-a(2,1))/a(2,2)
end if
vec_norm(2,x)
ev(1,j)=x(1) ! ev(2,j)=x(2)
next j
end def
{/matlib}