1 ! Copyright (C) 2013 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors arrays fry kernel locals math math.matrices
4 math.vectors sequences sequences.private ;
5 IN: math.matrices.laplace
9 : 2x2-determinant ( matrix -- x )
10 first2 [ first2 ] bi@ -rot [ * ] 2bi@ - ;
12 ! using a virtual "missing element" sequence for performance
13 TUPLE: missing seq i ;
16 [ i>> dupd >= [ 1 + ] when ] [ seq>> nth-unsafe ] bi ;
17 M: missing length seq>> length 1 - ;
18 INSTANCE: missing immutable-sequence
20 : first-sub-matrix ( matrix -- first-row seq )
21 [ unclip-slice swap ] [ length iota ] bi
22 [ '[ _ <missing> ] map ] with map ;
24 :: laplace-expansion ( row matrix -- x )
26 [ matrix 2x2-determinant ] [
27 matrix first-sub-matrix ! cheat, always expand on first row
28 [ row swap laplace-expansion ] map
29 v* [ odd? [ neg ] when ] map-index sum
32 ERROR: not-a-square-matrix matrix ;
34 : check-square-matrix ( matrix -- matrix )
35 dup square-matrix? [ not-a-square-matrix ] unless ; inline
39 : determinant ( matrix -- x )
40 check-square-matrix 0 swap laplace-expansion ;