Skip to content

Instantly share code, notes, and snippets.

@heatherm
Created October 27, 2013 05:10
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 heatherm/7178194 to your computer and use it in GitHub Desktop.
Save heatherm/7178194 to your computer and use it in GitHub Desktop.
matrix multiplication by columns
def multiply left_matrix, right_matrix
right_matrix_transposed = transpose right_matrix
result = left_matrix.each.map { [] }
right_matrix_transposed.each do |column|
left_matrix.each_with_index do |row, row_index|
sum = 0
row.each_with_index do |row_value, position_index|
sum += row_value*column[position_index]
end
result[row_index].push(sum)
end
end
result
end
def transpose matrix
right_matrix_transposed = matrix[0].map { [] }
matrix.each do |row|
row.each_with_index do |row_value, new_row|
right_matrix_transposed[new_row].push(row_value)
end
end
right_matrix_transposed
end
require 'benchmark'
require 'matrix'
Benchmark.bm do |b|
b.report("multiply_by_columns") do
1_000_000.times { multiply [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[2, 4, 6], [3, 1, 2], [8, 8, 4]] }
end
b.report("Matrix#* Ruby 2.0") do
a = Matrix[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = Matrix[[2, 4, 6], [3, 1, 2], [8, 8, 4]]
1_000_000.times { a * b }
end
end
Benchmark.bm do |b|
b.report("multiply") do
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [11, 22, 33]]
c = [[2, 4, 6, 6, 7, 7], [3, 1, 2, 6, 7, 7], [8, 8, 4, 6, 7, 7]]
1_000_000.times { multiply a, c }
end
b.report("Matrix#* Ruby 2.0") do
a = Matrix[[1, 2, 3], [4, 5, 6], [7, 8, 9], [11, 22, 33]]
c = Matrix[[2, 4, 6, 6, 7, 7], [3, 1, 2, 6, 7, 7], [8, 8, 4, 6, 7, 7]]
1_000_000.times { a * c }
end
end
# RESULTS for 1_000_000 times on 3x3*3x3
# user system total real
#mine 17.100000 0.010000 17.110000 ( 17.105483)
#ruby 20.850000 0.020000 20.870000 ( 20.873743)
# RESULTS for 1_000_000 times on 4x3*3x6
# user system total real
#mine 37.030000 0.020000 37.050000 ( 37.050012)
#ruby 54.390000 0.030000 54.420000 ( 54.431502)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment