From 07fd6dc49ba87ea2f0732851ec7628a526f3dcbd Mon Sep 17 00:00:00 2001 From: Marc-Andre Lafortune Date: Thu, 30 Apr 2020 17:04:46 -0400 Subject: [PATCH] [ruby/matrix] Optimize Matrix#* --- lib/matrix.rb | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/lib/matrix.rb b/lib/matrix.rb index 7d35b61fc5..75b5da29c7 100644 --- a/lib/matrix.rb +++ b/lib/matrix.rb @@ -1057,25 +1057,27 @@ class Matrix def *(m) # m is matrix or vector or number case(m) when Numeric - rows = @rows.collect {|row| + new_rows = @rows.collect {|row| row.collect {|e| e * m } } - return new_matrix rows, column_count + return new_matrix new_rows, column_count when Vector m = self.class.column_vector(m) r = self * m return r.column(0) when Matrix raise ErrDimensionMismatch if column_count != m.row_count - - rows = Array.new(row_count) {|i| - Array.new(m.column_count) {|j| - (0 ... column_count).inject(0) do |vij, k| - vij + self[i, k] * m[k, j] + m_rows = m.rows + new_rows = rows.map do |row_i| + Array.new(m.column_count) do |j| + vij = 0 + column_count.times do |k| + vij += row_i[k] * m_rows[k][j] end - } - } - return new_matrix rows, m.column_count + vij + end + end + return new_matrix new_rows, m.column_count else return apply_through_coercion(m, __method__) end