Rosetta Code

Matrix multiplication

Multiply two small matrices and return the deterministic product matrix.

Medium View source
Source rosettacode/popular/matrix_multiplication.vibe
# title: Matrix multiplication
# source: https://rosettacode.org/wiki/Matrix_multiplication
# category: Rosetta Code
# difficulty: Medium
# summary: Multiply two small matrices and return the deterministic product matrix.
# tags: popular, math, arrays, nested-loops
# vibe: 0.2

def matrix_multiply(left, right)
  product = []
  row_index = 0

  while row_index < left.size
    row = []
    column_index = 0

    while column_index < right[0].size
      total = 0
      inner_index = 0

      while inner_index < right.size
        total = total + (left[row_index][inner_index] * right[inner_index][column_index])
        inner_index = inner_index + 1
      end

      row = row.push(total)
      column_index = column_index + 1
    end

    product = product.push(row)
    row_index = row_index + 1
  end

  product
end

def run
  left = [
    [1, 2, 3],
    [4, 5, 6]
  ]

  right = [
    [7, 8],
    [9, 10],
    [11, 12]
  ]

  matrix_multiply(left, right)
end
Output
Press run to execute run from this example.
rosetta-code popular math arrays nested-loops browser-runner