summaryrefslogtreecommitdiff
path: root/lib/matrix.rb
diff options
context:
space:
mode:
authormarcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2014-04-06 17:46:16 +0000
committermarcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2014-04-06 17:46:16 +0000
commitd11d87c3627e60a957f9313d2106f7a6d2b5f7a1 (patch)
treedb5bc7ce26a2794cc82504950d045c9f7691b584 /lib/matrix.rb
parentb8ba202301e5e4cf392a827c9bb8ebf2265de99f (diff)
* lib/matrix.rb: Add Matrix#cofactor [fix GH-568]
Patch by gogotanaka git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@45528 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'lib/matrix.rb')
-rw-r--r--lib/matrix.rb17
1 files changed, 17 insertions, 0 deletions
diff --git a/lib/matrix.rb b/lib/matrix.rb
index 7502e6e..1a7519f 100644
--- a/lib/matrix.rb
+++ b/lib/matrix.rb
@@ -59,6 +59,7 @@ end
# * #find_index
# * #minor(*param)
# * #first_minor(row, column)
+# * #cofactor(row, column)
#
# Properties of a matrix:
# * #diagonal?
@@ -545,6 +546,7 @@ class Matrix
nil
end
alias_method :find_index, :index
+
#
# Returns a section of the matrix. The parameters are either:
# * start_row, nrows, start_col, ncols; OR
@@ -619,6 +621,21 @@ class Matrix
new_matrix arrays, column_count - 1
end
+ #
+ # Returns the (row, column) cofactor which is obtained by multiplying
+ # the first minor by (-1)**(row + column).
+ #
+ # Matrix.diagonal(9, 5, -3, 4).cofactor(1, 1)
+ # => -108
+ #
+ def cofactor(row, column)
+ raise RuntimeError, "cofactor of empty matrix is not defined" if empty?
+ Matrix.Raise ErrDimensionMismatch unless square?
+
+ det_of_minor = first_minor(row, column).determinant
+ det_of_minor * (-1) ** (row + column)
+ end
+
#--
# TESTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++