Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,849 questions

55,678 answers

573 users

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 May 25 by avibootz
...