diff --git a/NEWS b/NEWS index b85aed1..6a6585c 100644 --- a/NEWS +++ b/NEWS @@ -59,6 +59,7 @@ with all sufficient information, see the ChangeLog file. by deleting the specified row and column. * Matrix#cofactor(row, column) returns the (row, column) cofactor which is obtained by multiplying the first minor by (-1)**(row + column). + * Matrix#adjugate returns the adjugate of the matrix. * Method * New methods: diff --git a/lib/matrix.rb b/lib/matrix.rb index 026492b..774cd3d 100644 --- a/lib/matrix.rb +++ b/lib/matrix.rb @@ -60,6 +60,7 @@ end # * #minor(*param) # * #first_minor(row, column) # * #cofactor(row, column) +# * #adjugate # # Properties of a matrix: # * #diagonal? @@ -636,6 +637,20 @@ class Matrix det_of_minor * (-1) ** (row + column) end + # + # Returns the adjugate of the matrix. + # + # Matrix[ [7,6],[3,9] ].adjugate + # => 9 -6 + # -3 7 + # + def adjugate + Matrix.Raise ErrDimensionMismatch unless square? + Matrix.build(row_count, column_count) do |row, column| + cofactor(column, row) + end + end + #-- # TESTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ diff --git a/test/matrix/test_matrix.rb b/test/matrix/test_matrix.rb index e38db70..a5cc516 100644 --- a/test/matrix/test_matrix.rb +++ b/test/matrix/test_matrix.rb @@ -273,6 +273,17 @@ class TestMatrix < Test::Unit::TestCase assert_raise(ExceptionForMatrix::ErrDimensionMismatch) { Matrix[[2,0,1],[0,-2,2]].cofactor(0, 0) } end + def test_adjugate + assert_equal(Matrix.empty, Matrix.empty.adjugate) + assert_equal(Matrix[[1]], Matrix[[5]].adjugate) + assert_equal(Matrix[[0,0],[0,0]], Matrix[[0,0],[0,0]].adjugate) + assert_equal(Matrix[[9,-6],[-3,7]], Matrix[[7,6],[3,9]].adjugate) + assert_equal(Matrix[[45,3,-7],[6,-1,0],[-7,0,0]], Matrix[[0,0,1],[0,7,6],[1,3,9]].adjugate) + m = Matrix[[2, 0, 9, 3, 9], [8, 7, 0, 1, 9], [7, 5, 6, 6, 5], [0, 7, 8, 3, 0], [7, 8, 2, 3, 1]] + assert_equal(Matrix.identity(5), (m.adjugate * m) / m.det) + assert_raise(ExceptionForMatrix::ErrDimensionMismatch) { @m1.adjugate } + end + def test_regular? assert(Matrix[[1, 0], [0, 1]].regular?) assert(Matrix[[1, 0, 0], [0, 1, 0], [0, 0, 1]].regular?)