diff options
author | marcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2017-11-20 02:18:43 +0000 |
---|---|---|
committer | marcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2017-11-20 02:18:43 +0000 |
commit | b1152fab0f5e48ce641b8b61f9d2565eff9187f3 (patch) | |
tree | ee92df24c9e490fdc44947e52e10d6e0cc0a4a42 | |
parent | 980c0dd360b5454d49df47e08b8708ff888ae7a4 (diff) | |
download | ruby-b1152fab0f5e48ce641b8b61f9d2565eff9187f3.tar.gz |
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
-rw-r--r-- | lib/matrix.rb | 11 | ||||
-rw-r--r-- | test/matrix/test_matrix.rb | 14 |
2 files changed, 25 insertions, 0 deletions
diff --git a/lib/matrix.rb b/lib/matrix.rb index 2f2d0f371a..d242665ef9 100644 --- a/lib/matrix.rb +++ b/lib/matrix.rb @@ -980,6 +980,17 @@ class Matrix 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. # Matrix[[-1, -1], [0, -1]].inverse # => -1 1 diff --git a/test/matrix/test_matrix.rb b/test/matrix/test_matrix.rb index 92a24d1e9f..d40e0c0430 100644 --- a/test/matrix/test_matrix.rb +++ b/test/matrix/test_matrix.rb @@ -418,6 +418,20 @@ class TestMatrix < Test::Unit::TestCase assert_equal(Matrix[[1,1],[1,1]], Matrix[[2,2],[2,2]] / o) 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 assert_equal(Matrix[[67,96],[48,99]], Matrix[[7,6],[3,9]] ** 2) assert_equal(Matrix.I(5), Matrix.I(5) ** -1) |