diff --git a/basis/math/matrices/matrices-tests.factor b/basis/math/matrices/matrices-tests.factor index 3996a475ba..4e3cf06667 100644 --- a/basis/math/matrices/matrices-tests.factor +++ b/basis/math/matrices/matrices-tests.factor @@ -7,14 +7,84 @@ USING: math.matrices math.vectors tools.test math ; 3 1 zero-matrix ] unit-test -[ +{ { { 1 0 0 } { 0 1 0 } { 0 0 1 } } -] [ +} [ 3 identity-matrix ] unit-test +{ + { { 1 0 0 } + { 0 2 0 } + { 0 0 3 } } +} [ + { 1 2 3 } diagonal-matrix +] unit-test + +{ + { + { 1 0 0 } + { 0 1 0 } + { 0 0 1 } + } +} [ + 3 3 0 eye +] unit-test + +{ + { + { 0 1 0 } + { 0 0 1 } + { 0 0 0 } + } +} [ + 3 3 1 eye +] unit-test + +{ + { + { 0 0 0 } + { 1 0 0 } + { 0 1 0 } + } +} [ + 3 3 -1 eye +] unit-test + +{ + { + { 1 0 0 0 } + { 0 1 0 0 } + { 0 0 1 0 } + } +} [ + 3 4 0 eye +] unit-test + +{ + { + { 0 1 0 } + { 0 0 1 } + { 0 0 0 } + { 0 0 0 } + } +} [ + 4 3 1 eye +] unit-test + +{ + { + { 0 0 0 } + { 1 0 0 } + { 0 1 0 } + { 0 0 1 } + } +} [ + 4 3 -1 eye +] unit-test + [ { { 1 0 4 } { 0 7 0 } diff --git a/basis/math/matrices/matrices.factor b/basis/math/matrices/matrices.factor index 9fc4f879e8..763b133cf3 100644 --- a/basis/math/matrices/matrices.factor +++ b/basis/math/matrices/matrices.factor @@ -9,9 +9,15 @@ IN: math.matrices : zero-matrix ( m n -- matrix ) '[ _ 0 ] replicate ; +: diagonal-matrix ( diagonal-seq -- matrix ) + dup length dup zero-matrix + [ '[ dup _ nth set-nth ] each-index ] keep ; inline + : identity-matrix ( n -- matrix ) - #! Make a nxn identity matrix. - iota dup [ = 1 0 ? ] cartesian-map ; + 1 diagonal-matrix ; inline + +: eye ( m n k -- matrix ) + [ [ iota ] bi@ ] dip neg '[ _ + = 1 0 ? ] cartesian-map ; :: rotation-matrix3 ( axis theta -- matrix ) theta cos :> c