If you interested in finding the determinant of a matrix, the easiest way
is probably to bind to LAPACK or LINPACK using our Fortran FFI. Take a look
at extra/math/blas/ffi for an example.

I ended up writing the whole thing... It's really inefficient, as it makes
temporary matrices.  You'd probably want some kind of virtual-matrix or
matrix view with the row/column removed.

: 2x2-det ( mat -- x )
    first2 [ [ first ] [ second ] bi* * ] [ [ second ] [ first ] bi* * ]
2bi - ;

: row-col-pairs ( row matrix -- seq )
    2dup length < [ nip 0 swap ] unless
    length iota [ 2array ] with map ;

: sub-matrices ( row matrix -- seq )
    [ nip ] [ row-col-pairs ] 2bi
    [ first2 [ swap remove-nth ] dip '[ _ swap remove-nth ] map ] with { }
map-as ;

:: laplace-expansion ( row matrix -- x )
    matrix length 2 = [ matrix 2x2-det ] [
        0 matrix [ nth ] [ sub-matrices ] 2bi  ! cheat, always expand on
first row for recursive case
        [ row swap laplace-expansion ] map
        v* [ odd? [ neg ] when ] map-index sum
    ] if ;

: determinant ( matrix -- x )
    ! TODO: Check for square matrix here
    0 swap laplace-expansion ;

0 { { 1 2 3 } { 4 5 6 } { 7 8 9 } } laplace-expansion .
0
1 { { 1 2 3 } { 4 5 6 } { 7 8 9 } } laplace-expansion .
0
2 { { 1 2 3 } { 4 5 6 } { 7 8 9 } } laplace-expansion .
0

{ { 40 39 38 37 } { 1 1 1 831 } { 22 22 1110 299 } { 13 14 15 17 } }
determinant
http://www.wolframalpha.com/input/?i=Determinant%5B%5B40%2C39%2C38%2C37%5D%2C%5B1%2C1%2C1%2C831%5D%2C%5B22%2C22%2C1110%2C299%5D%2C%5B13%2C14%2C15%2C17%5D%5D


If you have time, try adding a more efficient version to arrays.shaped? (Or
bind to LINPACK or implement a better algorithm!)

Have fun,
Doug


On Tue, Feb 5, 2013 at 1:32 PM, Leonard P <leonard14...@gmail.com> wrote:

> Anyone know off-hand of an idiomatic way to do the Laplace expansion of an
> nxn matrix?
>
>
>
>
> ------------------------------------------------------------------------------
> Free Next-Gen Firewall Hardware Offer
> Buy your Sophos next-gen firewall before the end March 2013
> and get the hardware for free! Learn more.
> http://p.sf.net/sfu/sophos-d2d-feb
> _______________________________________________
> Factor-talk mailing list
> Factor-talk@lists.sourceforge.net
> https://lists.sourceforge.net/lists/listinfo/factor-talk
>
>
------------------------------------------------------------------------------
Free Next-Gen Firewall Hardware Offer
Buy your Sophos next-gen firewall before the end March 2013 
and get the hardware for free! Learn more.
http://p.sf.net/sfu/sophos-d2d-feb
_______________________________________________
Factor-talk mailing list
Factor-talk@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/factor-talk

Reply via email to