How to implement matrix multiplication in Kotlin

1 Answer

0 votes
// Multiply rows of A by columns of B.

typealias Matrix = List<MutableList<Int>>

// Print a 2D array (matrix)
fun printMatrix(arr2d: Matrix) {
    for (row in arr2d) {
        for (value in row) {
            print("%4d".format(value))
        }
        println()
    }
}

// Multiply matrices A and B into C
fun multipleMatrix(a: Matrix, b: Matrix, c: Matrix) {
    for (i in c.indices) {
        for (j in c[i].indices) {
            for (k in a[i].indices) {
                c[i][j] += a[i][k] * b[k][j]
            }
        }
    }
}

fun main() {
    // Create matrices
    val a: Matrix = listOf(
        mutableListOf(1, 8, 5),
        mutableListOf(6, 7, 1),
        mutableListOf(8, 7, 6)
    )

    val b: Matrix = listOf(
        mutableListOf(4, 8, 1),
        mutableListOf(6, 5, 3),
        mutableListOf(4, 6, 5)
    )

    // Initialize result matrix C with zeros
    val c: Matrix = List(a.size) {
        MutableList(b[0].size) { 0 }
    }

    // c[0][0] = (a[0][0] * b[0][0]) + (a[0][1] * b[1][0]) + (a[0][2] * b[2][0])

    printMatrix(a)
    println()
    printMatrix(b)
    println()

    multipleMatrix(a, b, c)

    printMatrix(c)
}


/*
run:
        
     1   8   5
     6   7   1
     8   7   6
    
     4   8   1
     6   5   3
     4   6   5
    
    72  78  50
    70  89  32
    98 135  59
    
*/

 



answered May 25 by avibootz
...