New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add cofactor and first_minor methods for the Matrix class #568

Closed
wants to merge 9 commits into
base: trunk
from
Next

Add first_minor method for Matrix class

  • Loading branch information...
gogotanaka committed Mar 16, 2014
commit 630472f84a8f384db59c15bab2b1d5ffdc4a5e30
View
@@ -58,6 +58,7 @@ module ExceptionForMatrix # :nodoc:
# * #each_with_index
# * #find_index
# * #minor(*param)
# * #first_minor(row, column)
#
# Properties of a matrix:
# * #diagonal?
@@ -589,6 +590,34 @@ def minor(*param)
new_matrix rows, [column_count - from_col, size_col].min
end
#
# Returns a the submatrix formed by deleting the i-th row and j-th column.
#
# Matrix.diagonal(9, 5, -3, 4).first_minor(1, 2)
# => 9 0 0
# 0 0 0
# 0 0 4
#
def first_minor(row, column)
raise TypeError, "first_minor of empty matrix is not defined" if empty?
unless 0 <= row && row < row_count
raise ArgumentError, "expected #{row.inspect} to be 0 to #{row_count - 1}"
end
unless 0 <= column && column < column_count
raise ArgumentError, "expected #{column.inspect} to be 0 to #{column_count - 1}"
end
arrays = to_a
arrays.delete_at(row)
arrays.each do |array|
array.delete_at(column)
end
new_matrix arrays, column_count - 1
end
#--
# TESTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++
View
@@ -246,6 +246,17 @@ def test_minor
assert_raise(ArgumentError) { @m1.minor(0) }
end
def test_first_minor
assert_equal(Matrix.empty(0, 0), Matrix[[1]].first_minor(0, 0))
assert_equal(Matrix[[1, 3]], @m1.first_minor(1, 1))
assert_equal(Matrix[[4, 6]], @m1.first_minor(0, 1))
assert_equal(Matrix[[1, 2]], @m1.first_minor(1, 2))
assert_raise(TypeError) { Matrix.empty(0, 0).first_minor(0, 0) }
assert_raise(ArgumentError) { @m1.first_minor(4, 0) }
assert_raise(ArgumentError) { @m1.first_minor(0, -1) }
assert_raise(ArgumentError) { @m1.first_minor(-1, 4) }
end
def test_regular?
assert(Matrix[[1, 0], [0, 1]].regular?)
assert(Matrix[[1, 0, 0], [0, 1, 0], [0, 0, 1]].regular?)
ProTip! Use n and p to navigate between commits in a pull request.