Version 0 of Matrix determinant

Updated 2004-03-14 10:11:08

if 0 {Richard Suchenwirth 2004-03-14 - The determinant of a square matrix is a scalar number that can be used for characterizing it (see http://mathworld.wolfram.com/Determinant.html : "If the determinant of a matrix is 0, the matrix is said to be singular, and if the determinant is 1, the matrix is said to be unimodular"). Here's some weekend fun code to compute the determinant of a matrix, represented as a list of lists:}

 proc det matrix {
    if {[llength $matrix] != [llength [lindex $matrix 0]]} {
       error "non-square matrix"
    }
    switch [llength $matrix] {
       2 {
            foreach {a b c d} [join $matrix] break
            expr {$a*$d - $b*$c}
       } default {
           set i 0
           set  mat2 [lrange $matrix 1 end]
           set res 0
           foreach  element [lindex $matrix 0] {
              if $element {
                 set sign [expr {$i%2? -1: 1}]
                 set res [expr {$res + $sign*$element* [det [cancelcol $i $mat2]]}]
              }
              incr i
           }
           set res 
       }
    }
 }
 proc cancelcol {n matrix} {
    set res {}
    foreach row $matrix {
        lappend res [lreplace $row $n $n]
    }
    set res
 }

if 0 {Some tests, to see whether this code agrees with the examples in my math book:

 % det {{5 -3 2} {1 0 6} {3 1 -2}}
 -88
 % det {{1 0 0} {0 1 0} {0 0 1}}
 1
 % det {{1 2} {3 4}}
 -2
 % det {{2 4} {1 3}}
 2
 % det {{1 2 -1} {-2 1 3} {3 0 -2}}
 11
 % det {{1 2 -1 0} {-2 1 3 1} {3 0 -2 2} {1 2 3 4}}
 -20
 % det {{1 1 1} {1 1 1} {1 1 1}}
 0

Arts and crafts of Tcl-Tk programming