' ******************************************************************
' Eigenvalues of a general square matrix
' ******************************************************************

#INCLUDE "fbmath.bi"

SUB WriteEigenValue(Lambda AS Complex)
' Writes eigenvalue Lambda

  IF Lambda.Y = 0 THEN
    PRINT USING "#####.######"; Lambda.X
  ELSE
    PRINT USING "#####.######"; Lambda.X;
    IF Lambda.Y > 0 THEN PRINT " + ";  ELSE PRINT " - ";
    PRINT USING "#####.######"; ABS(Lambda.Y); " * i"
  END IF
END SUB

CONST N = 4                          ' Size of matrix

DIM AS DOUBLE A(1 TO N, 1 TO N) = _  ' Original matrix
{{ 1, 2, 0, -1},   _
 {-1, 4, 3, -0.5}, _
 { 2, 2, 1, -3},   _
 { 0, 0, 3, -4}}

DIM AS Complex Lambda(1 TO N)        ' Eigenvalues

DIM AS INTEGER I, ErrCode

EigenVals A(), Lambda()

ErrCode = MathErr

IF ErrCode = 0 THEN
  PRINT "Eigenvalues:"
  PRINT
  FOR I = 1 TO N
    WriteEigenValue Lambda(I)
  NEXT I
ELSE
  PRINT "Unable to find eigenvalues Lambda(1) to Lambda("; -ErrCode; ")"
  PRINT
  IF 1 - ErrCode < N THEN
    PRINT "Eigenvalues Lambda("; 1 - ErrCode; ") to Lambda("; N; "):"
    FOR I = 1 - ErrCode TO N
      WriteEigenValue Lambda(I)
    NEXT I
   END IF
END IF

SLEEP
