How to implement matrix multiplication in Ruby

1 Answer

0 votes
# Multiply rows of A by columns of B.

# Print a 2D array (matrix)
def print_matrix(arr2d)
  arr2d.each do |row|
    row.each do |val|
      print val.to_s.rjust(4)
    end
    puts
  end
end

# Multiply matrices A and B into C
def multiple_matrix(a, b, c)
  (0...c.length).each do |i|
    (0...c[i].length).each do |j|
      (0...a[i].length).each do |k|
        c[i][j] += a[i][k] * b[k][j]
      end
    end
  end
end

# Create matrices
a = [
  [1, 8, 5],
  [6, 7, 1],
  [8, 7, 6]
]

b = [
  [4, 8, 1],
  [6, 5, 3],
  [4, 6, 5]
]

# Initialize result matrix C with zeros
c = Array.new(a.length) { Array.new(b[0].length, 0) }

# c[0, 0] = (a[0][0] * b[0][0]) + (a[0][1] * b[1][0]) + (a[0][2] * b[2][0])

print_matrix(a)
puts
print_matrix(b)
puts

multiple_matrix(a, b, c)

print_matrix(c)



=begin
run:
        
     1   8   5
     6   7   1
     8   7   6
    
     4   8   1
     6   5   3
     4   6   5
    
    72  78  50
    70  89  32
    98 135  59

=end

 



answered 2 days ago by avibootz
...