Scala program to perform matrix multiplication

1. Introduction

Matrix multiplication is a fundamental operation in linear algebra and finds wide applications in areas like computer graphics, physics simulations, and machine learning, to name a few. In this post, we'll walk through a Scala program that multiplies two matrices.

2. Program Steps

1. Set up the Scala environment.

2. Create an object to house the main function.

3. Define two matrices to be multiplied.

4. Implement the matrix multiplication function.

5. Call the function within the main method to multiply the matrices.

6. Print the resulting matrix.

7. Run the program.

3. Code Program

object MatrixMultiplicationApp {
  def main(args: Array[String]): Unit = {
    // Define two matrices
    val matrix1 = Array(Array(1, 2), Array(3, 4))
    val matrix2 = Array(Array(2, 0), Array(1, 3))

    println("Matrix 1:")
    matrix1.foreach(row => println(row.mkString(" ")))

    println("\nMatrix 2:")
    matrix2.foreach(row => println(row.mkString(" ")))

    // Multiply the matrices
    val resultMatrix = multiplyMatrices(matrix1, matrix2)

    println("\nResultant Matrix:")
    resultMatrix.foreach(row => println(row.mkString(" ")))
  }

  // Function to multiply two matrices
  def multiplyMatrices(mat1: Array[Array[Int]], mat2: Array[Array[Int]]): Array[Array[Int]] = {
    val rowsMat1 = mat1.length
    val colsMat1 = mat1(0).length
    val colsMat2 = mat2(0).length

    // Initializing the resultant matrix with zeros
    val result = Array.ofDim[Int](rowsMat1, colsMat2)

    for (i <- 0 until rowsMat1; j <- 0 until colsMat2) {
      for (k <- 0 until colsMat1) {
        result(i)(j) += mat1(i)(k) * mat2(k)(j)
      }
    }
    result
  }
}

Output:

Matrix 1:
1 2
3 4
Matrix 2:
2 0
1 3
Resultant Matrix:
4 6
10 12

Explanation:

1. We initiate with an object named MatrixMultiplicationApp. In Scala, the main method, which serves as the program's entry point, resides inside an object.

2. We define two matrices, matrix1 and matrix2, to be multiplied.

3. These matrices are printed for clarity.

4. The function multiplyMatrices houses the logic to multiply two matrices. It first determines the dimensions of the matrices to initialize the resultant matrix. Then, using nested loops, it performs the multiplication operation and stores the result.

5. Once the matrices are multiplied, the resulting matrix is printed to the console.

6. When executed, the program displays the two input matrices and their multiplication result.


Comments