How to multiply two matrices in Scala

1 Answer

0 votes
object MatrixMultiplicationManual {
  def multiplyMatrices(matrix1: Array[Array[Int]], matrix2: Array[Array[Int]]): Array[Array[Int]] = {
    val rows1 = matrix1.length
    val cols1 = matrix1(0).length
    val rows2 = matrix2.length
    val cols2 = matrix2(0).length

    if (cols1 != rows2) {
      throw new IllegalArgumentException("Matrices cannot be multiplied: incompatible dimensions.")
    }

    val result = Array.ofDim[Int](rows1, cols2)

    for (i <- 0 until rows1) {
      for (j <- 0 until cols2) {
        for (k <- 0 until cols1) {
          result(i)(j) += matrix1(i)(k) * matrix2(k)(j)
        }
      }
    }

    result
  }

  def main(args: Array[String]): Unit = {
    val matrix1 = Array(
      Array(1, 2, 3),
      Array(4, 5, 6),
      Array(7, 8, 9)
    )

    val matrix2 = Array(
      Array(4, 6),
      Array(7, 3),
      Array(1, 2)
    )

    try {
      val result = multiplyMatrices(matrix1, matrix2)

      result.foreach(row => println(row.mkString(" ")))
    } catch {
      case e: IllegalArgumentException => println(e.getMessage)
    }
  }
}



/*
run:

21 18
57 51
93 84
 
*/

 



answered Mar 4, 2025 by avibootz
...