Skip to content

Instantly share code, notes, and snippets.

@headius
Created July 7, 2015 01:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save headius/317e7bf0617cff8e92e7 to your computer and use it in GitHub Desktop.
Save headius/317e7bf0617cff8e92e7 to your computer and use it in GitHub Desktop.
diff --git a/lib/ruby/stdlib/matrix.rb b/lib/ruby/stdlib/matrix.rb
index fb98d09..b387069 100644
--- a/lib/ruby/stdlib/matrix.rb
+++ b/lib/ruby/stdlib/matrix.rb
@@ -368,14 +368,16 @@ class Matrix
#
# Returns element (+i+,+j+) of the matrix. That is: row +i+, column +j+.
#
+ NIL_ARY = []
+ NIL_ARY_PROC = proc {NIL_ARY}
def [](i, j)
- @rows.fetch(i){return nil}[j]
+ @rows.fetch(i, &NIL_ARY_PROC).at(j)
end
alias element []
alias component []
def []=(i, j, v)
- @rows[i][j] = v
+ @rows.at(i)[j] = v
end
alias set_element []=
alias set_component []=
@@ -961,21 +963,36 @@ class Matrix
r = self * m
return r.column(0)
when Matrix
- 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]
- end
- }
- }
- return new_matrix rows, m.column_count
+ return _multiply_matrix(m)
else
return apply_through_coercion(m, __method__)
end
end
+ private def _multiply_matrix(m)
+ Matrix.Raise ErrDimensionMismatch if column_count != m.row_count
+
+ m_column_count = m.column_count
+ rows = Array.new(row_count)
+ i = 0
+ while i < row_count
+ rows[i] = row = Array.new(m_column_count)
+ j = 0
+ while j < m_column_count
+ k = 0
+ vij = 0
+ while k < column_count
+ vij = vij + self[i, k] * m[k, j]
+ k += 1
+ end
+ row[j] = vij
+ j+=1
+ end
+ i += 1
+ end
+ return new_matrix rows, m.column_count
+ end
+
#
# Matrix addition.
# Matrix.scalar(2,5) + Matrix[[1,0], [-4,7]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment