' ******************************************************************
' Determinant and inverse of a square matrix
' ******************************************************************

#INCLUDE "fbmath.bi"

SUB PrintMatrix(Title AS STRING, A() AS DOUBLE)

  DIM AS INTEGER I, J

  PRINT : PRINT Title : PRINT

  FOR I = 1 TO UBOUND(A, 1)
    FOR J = 1 TO UBOUND(A, 2)
      PRINT USING "#####.######"; A(I, J);
    NEXT J
    PRINT
  NEXT I
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 DOUBLE  Det                   ' Determinant
DIM AS INTEGER ErrCode               ' Error code

CLS

PrintMatrix "Original matrix:", A()

GaussJordan A(), Det

SELECT CASE MathErr
  CASE MatOk
    PrintMatrix "Inverse matrix:", A()
    PRINT : PRINT "Determinant =", Det

    GaussJordan A(), Det

    IF MathErr = MatOk THEN
      PrintMatrix "Reinverted inverse matrix:", A()
    END IF
  CASE MatErrDim
    PRINT "Non-compatible dimensions!"
  CASE MatSing
    PRINT "Quasi-singular matrix!"
END SELECT

SLEEP
