[前][次][番号順一覧][スレッド一覧]

ruby-changes:48744

From: marcandre <ko1@a...>
Date: Mon, 20 Nov 2017 11:24:17 +0900 (JST)
Subject: [ruby-changes:48744] marcandRe: r60860 (trunk): lib/matrix: Add hadamard_product/entrywise_product.

marcandre	2017-11-20 11:18:43 +0900 (Mon, 20 Nov 2017)

  New Revision: 60860

  https://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=revision&revision=60860

  Log:
    lib/matrix: Add hadamard_product/entrywise_product.
    
    Based on a patch by Charley Hutchison. [GH-674]

  Modified files:
    trunk/lib/matrix.rb
    trunk/test/matrix/test_matrix.rb
Index: lib/matrix.rb
===================================================================
--- lib/matrix.rb	(revision 60859)
+++ lib/matrix.rb	(revision 60860)
@@ -980,6 +980,17 @@ class Matrix https://github.com/ruby/ruby/blob/trunk/lib/matrix.rb#L980
   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
Index: test/matrix/test_matrix.rb
===================================================================
--- test/matrix/test_matrix.rb	(revision 60859)
+++ test/matrix/test_matrix.rb	(revision 60860)
@@ -418,6 +418,20 @@ class TestMatrix < Test::Unit::TestCase https://github.com/ruby/ruby/blob/trunk/test/matrix/test_matrix.rb#L418
     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)

--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]