summaryrefslogtreecommitdiff
path: root/lib/matrix.rb
diff options
context:
space:
mode:
authormarcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2014-10-07 19:30:48 +0000
committermarcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2014-10-07 19:30:48 +0000
commit56d5728589f9cfea6e1d923d5faab8f1b982d29d (patch)
tree67dec8bb485fe4cc060ec59dfd7116caa205cac2 /lib/matrix.rb
parent19a1257d6c941fec8526a67037d21c66c0c3d811 (diff)
* lib/matrix.rb: Add Matrix#laplace_expansion.
patch by gogo tanaka [#10073] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@47835 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'lib/matrix.rb')
-rw-r--r--lib/matrix.rb33
1 files changed, 33 insertions, 0 deletions
diff --git a/lib/matrix.rb b/lib/matrix.rb
index 054c197..b56b128 100644
--- a/lib/matrix.rb
+++ b/lib/matrix.rb
@@ -62,6 +62,8 @@ end
# * #minor(*param)
# * #first_minor(row, column)
# * #cofactor(row, column)
+# * #laplace_expansion(row_or_column: num)
+# * #cofactor_expansion(row_or_column: num)
#
# Properties of a matrix:
# * #diagonal?
@@ -685,6 +687,37 @@ class Matrix
det_of_minor * (-1) ** (row + column)
end
+ #
+ # Returns the Laplace expansion along given row or column.
+ #
+ # Matrix[[7,6], [3,9]].laplace_expansion(column: 1)
+ # => 45
+ #
+ # Matrix[[Vector[1, 0], Vector[0, 1]], [2, 3]].laplace_expansion(row: 0)
+ # => Vector[3, -2]
+ #
+ #
+ def laplace_expansion(row: nil, column: nil)
+ num = row || column
+
+ if !num || (row && column)
+ raise ArgumentError, "exactly one the row or column arguments must be specified"
+ end
+
+ Matrix.Raise ErrDimensionMismatch unless square?
+ raise RuntimeError, "laplace_expansion of empty matrix is not defined" if empty?
+
+ unless 0 <= num && num < row_count
+ raise ArgumentError, "invalid num (#{num.inspect} for 0..#{row_count - 1})"
+ end
+
+ send(row ? :row : :column, num).map.with_index { |e, k|
+ e * cofactor(*(row ? [num, k] : [k,num]))
+ }.inject(:+)
+ end
+ alias_method :cofactor_expansion, :laplace_expansion
+
+
#--
# TESTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++