Kotlin Program to Multiply Two Matrices by Passing Matrices to a Function

Multiplying two matrices involves performing a series of dot products between rows and columns to obtain the resulting matrix. This article presents three different Kotlin Program to Multiply Two Matrices by Passing Matrices to a Function, providing real examples with varying solutions and outputs.

1. Using Nested Loops

1.1 Example 1: Multiplying Two Matrices of Size 2×3 and 3×2

Kotlin
fun main() {
    val matrix1 = arrayOf(
        intArrayOf(1, 2, 3),
        intArrayOf(4, 5, 6)
    )
    val matrix2 = arrayOf(
        intArrayOf(7, 8),
        intArrayOf(9, 10),
        intArrayOf(11, 12)
    )
    
    val resultMatrix = multiplyMatrices(matrix1, matrix2)
    
    println("Matrix 1:")
    printMatrix(matrix1)
    
    println("\nMatrix 2:")
    printMatrix(matrix2)
    
    println("\nResultant Matrix:")
    printMatrix(resultMatrix)
}

fun printMatrix(matrix: Array<IntArray>) {
    for (row in matrix) {
        println(row.joinToString())
    }
}

fun multiplyMatrices(matrix1: Array<IntArray>, matrix2: Array<IntArray>): Array<IntArray> {
    val rows1 = matrix1.size
    val cols1 = matrix1[0].size
    val rows2 = matrix2.size
    val cols2 = matrix2[0].size
    
    require(cols1 == rows2) { "Matrices cannot be multiplied: columns of first matrix must match rows of second matrix" }
    
    val resultMatrix = Array(rows1) { IntArray(cols2) }
    
    for (i in 0 until rows1) {
        for (j in 0 until cols2) {
            var sum = 0
            for (k in 0 until cols1) {
                sum += matrix1[i][k] * matrix2[k][j]
            }
            resultMatrix[i][j] = sum
        }
    }
    
    return resultMatrix
}

Output:

Kotlin
Matrix 1:
1, 2, 3
4, 5, 6

Matrix 2:
7, 8
9, 10
11, 12

Resultant Matrix:
58, 64
139, 154

2. Using Extension Function

2.1 Example 2: Multiplying Two Matrices of Size 2×2 and 2×2

Kotlin
fun main() {
    val matrix1 = arrayOf(
        intArrayOf(1, 2),
        intArrayOf(3, 4)
    )
    val matrix2 = arrayOf(
        intArrayOf(5, 6),
        intArrayOf(7, 8)
    )
    
    val resultMatrix = matrix1.multiplyMatrices(matrix2)
    
    println("Matrix 1:")
    printMatrix(matrix1)
    
    println("\nMatrix 2:")
    printMatrix(matrix2)
    
    println("\nResultant Matrix:")
    printMatrix(resultMatrix)
}

fun printMatrix(matrix: Array<IntArray>) {
    for (row in matrix) {
        println(row.joinToString())
    }
}

fun Array<IntArray>.multiplyMatrices(other: Array<IntArray>): Array<IntArray> {
    require(this.isNotEmpty() && other.isNotEmpty()) { "Matrices cannot be empty" }
    require(this[0].size == other.size) { "Matrices cannot be multiplied: columns of first matrix must match rows of second matrix" }
    
    val rows = this.size
    val cols = other[0].size
    
    val resultMatrix = Array(rows) { IntArray(cols) }
    
    for (i in 0 until rows) {
        for (j in 0 until cols) {
            var sum = 0
            for (k in this[i].indices) {
                sum += this[i][k] * other[k][j]
            }
            resultMatrix[i][j] = sum
        }
    }
    
    return resultMatrix
}

Output:

Kotlin
Matrix 1:
1, 2
3, 4

Matrix 2:
5, 6
7, 8

Resultant Matrix:
19, 22
43, 50

3. Using Matrix Class

3.1 Example 3: Multiplying Two Matrices Using a Matrix Class

Kotlin
class Matrix(private val matrix: Array<IntArray>) {
    init {
        require(matrix.isNotEmpty()) { "Matrix must not be empty" }
    }

    fun multiply(other: Matrix): Matrix {
        require(matrix[0].size == other.matrix.size) { "Matrices cannot be multiplied: the number of columns in the first matrix must match the number of rows in the second matrix" }
        
        val rows = matrix.size
        val cols = other.matrix[0].size
        
        val resultMatrix = Array(rows) { IntArray(cols) }
        
        for (i in matrix.indices) {
            for (j in other.matrix[0].indices) {
                var sum = 0
                for (k in matrix[0].indices) {
                    sum += matrix[i][k] * other.matrix[k][j]
                }
                resultMatrix[i][j] = sum
            }
        }
        
        return Matrix(resultMatrix)
    }

    override fun toString(): String {
        return matrix.joinToString("\n") { it.joinToString() }
    }
}

fun main() {
    val matrix1 = Matrix(arrayOf(
        intArrayOf(1, 2),
        intArrayOf(3, 4)
    ))
    val matrix2 = Matrix(arrayOf(
        intArrayOf(5, 6),
        intArrayOf(7, 8)
    ))
    
    val resultMatrix = matrix1.multiply(matrix2)
    
    println("Matrix 1:")
    println(matrix1)
    
    println("\nMatrix 2:")
    println(matrix2)
    
    println("\nResultant Matrix:")
    println(resultMatrix)
}

Output:

Kotlin
Matrix 1:
1, 2
3, 4

Matrix 2:
5, 6
7, 8

Resultant Matrix:
19, 22
43, 50

Explanation and Summary

  • Example 1: Uses nested loops to multiply two matrices by passing them to a function. It calculates the dot product of rows and columns to generate the resultant matrix.
  • Example 2: Demonstrates an extension function approach, allowing matrices to directly perform multiplication operations, enhancing code readability and reusability.
  • Example 3: Utilizes a Matrix class to encapsulate matrix operations, providing a structured and object-oriented way to multiply matrices.

These examples showcase different methods to multiply matrices in Kotlin, each offering its advantages in terms of code structure, readability, and flexibility. Whether using traditional loops, extension functions, or a custom Matrix class, Kotlin provides powerful tools for matrix manipulation and mathematical operations.