mirror of
https://github.com/ruby/ruby.git
synced 2022-11-09 12:17:21 -05:00
lib/matrix: Add hadamard_product/entrywise_product.
Based on a patch by Charley Hutchison. [GH-674] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@60860 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
parent
980c0dd360
commit
b1152fab0f
2 changed files with 25 additions and 0 deletions
|
@ -979,6 +979,17 @@ class Matrix
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
#
|
||||||
|
# Hadamard product
|
||||||
|
# Matrix[[1,2], [3,4]].hadamard_product(Matrix[[1,2], [3,2]])
|
||||||
|
# => 1 4
|
||||||
|
# 9 8
|
||||||
|
#
|
||||||
|
def hadamard_product(m)
|
||||||
|
combine(m){|a, b| a * b}
|
||||||
|
end
|
||||||
|
alias_method :entrywise_product, :hadamard_product
|
||||||
|
|
||||||
#
|
#
|
||||||
# Returns the inverse of the matrix.
|
# Returns the inverse of the matrix.
|
||||||
# Matrix[[-1, -1], [0, -1]].inverse
|
# Matrix[[-1, -1], [0, -1]].inverse
|
||||||
|
|
|
@ -418,6 +418,20 @@ class TestMatrix < Test::Unit::TestCase
|
||||||
assert_equal(Matrix[[1,1],[1,1]], Matrix[[2,2],[2,2]] / o)
|
assert_equal(Matrix[[1,1],[1,1]], Matrix[[2,2],[2,2]] / o)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_hadamard_product
|
||||||
|
assert_equal(Matrix[[1,4], [9,16]], Matrix[[1,2], [3,4]].hadamard_product(Matrix[[1,2], [3,4]]))
|
||||||
|
assert_equal(Matrix[[2, 6, 12], [20, 30, 42]], @m1.hadamard_product(@n1))
|
||||||
|
o = Object.new
|
||||||
|
def o.to_matrix
|
||||||
|
Matrix[[1, 2, 3], [-1, 0, 1]]
|
||||||
|
end
|
||||||
|
assert_equal(Matrix[[1, 4, 9], [-4, 0, 6]], @m1.hadamard_product(o))
|
||||||
|
e = Matrix.empty(3, 0)
|
||||||
|
assert_equal(e, e.hadamard_product(e))
|
||||||
|
e = Matrix.empty(0, 3)
|
||||||
|
assert_equal(e, e.hadamard_product(e))
|
||||||
|
end
|
||||||
|
|
||||||
def test_exp
|
def test_exp
|
||||||
assert_equal(Matrix[[67,96],[48,99]], Matrix[[7,6],[3,9]] ** 2)
|
assert_equal(Matrix[[67,96],[48,99]], Matrix[[7,6],[3,9]] ** 2)
|
||||||
assert_equal(Matrix.I(5), Matrix.I(5) ** -1)
|
assert_equal(Matrix.I(5), Matrix.I(5) ** -1)
|
||||||
|
|
Loading…
Add table
Reference in a new issue