Skip to content

Instantly share code, notes, and snippets.

@halferty
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save halferty/9776963 to your computer and use it in GitHub Desktop.

Select an option

Save halferty/9776963 to your computer and use it in GitHub Desktop.
3x3 matrix multiplication - one way to do it
A = [[1,2,3],[4,5,6],[7,8,9]]
B = [[0,-10,20],[-30,40,-50],[60,-70,80]]
C = Array.new(A.size) { Array.new(B.size) }
B.size.times do |row|
B.first.size.times do |col|
column = B.map { |r| r[col] }
results = column.map.with_index { |item, index| item * A[(row) % B.first.size][index] }
C[(row) % B.size][col] = results.map { |item| item }.inject(&:+)
end
end
puts C.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment