Kotlin Program to Multiply Two Matrices Using Multi-dimensional Arrays

Multiplying two matrices involves performing dot products between rows and columns to obtain the resulting matrix. This article presents three different Kotlin programs to multiply matrices using multi-dimensional arrays, providing real examples with varying solutions and outputs.

1. Using Nested Loops

1.1 Example 1: Multiplying Two 2×2 Matrices

Uses nested loops to multiply two matrices of different sizes.

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

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
}

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

Output:

Kotlin
Matrix 1:
1, 2
3, 4

Matrix 2:
5, 6
7, 8

Resultant Matrix:
19, 22
43, 50

2. Using Extension Function

2.1 Example 2: Multiplying Two 3×3 Matrices

Demonstrates an extension function approach, allowing matrices to directly perform

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

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
}

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

Output:

Kotlin
Matrix 1:
1, 2, 3
4, 5, 6
7, 8, 9

Matrix 2:
9, 8, 7
6, 5, 4
3, 2, 1

Resultant Matrix:
30, 24, 18
84, 69, 54
138, 114, 90

3. Using Matrix Class

3.1 Example 3: Multiplying Two 2×3 and 3×2 Matrices Using a Matrix Class

Multiplication operations utilize a Matrix class to encapsulate matrix operations,

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

    fun multiply(other: Matrix): Matrix {
        require(matrix[0].size == other.matrix.size) { "Matrices cannot be multiplied: columns of first matrix must match rows of second matrix" }
        
        val rows = matrix.size
        val cols = other.matrix[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 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, 3),
        intArrayOf(4, 5, 6)
    ))
    val matrix2 = Matrix(arrayOf(
        intArrayOf(7, 8),
        intArrayOf(9, 10),
        intArrayOf(11, 12)
    ))
    
    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, 5, 6

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

Resultant Matrix:
58, 64
139, 154

Explanation and Summary

  • Example 1:
  • Example 2:
  • Example 3: