How to multiply two matrices in Kotlin

1 Answer

0 votes
fun multiplyMatrices(matrix1: Array<DoubleArray>, matrix2: Array<DoubleArray>): Array<DoubleArray> {
    val rows1 = matrix1.size
    val cols1 = matrix1[0].size
    val rows2 = matrix2.size
    val cols2 = matrix2[0].size

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

    val result = Array(rows1) { DoubleArray(cols2) }

    for (i in 0 until rows1) {
        for (j in 0 until cols2) {
            for (k in 0 until cols1) {
                result[i][j] += matrix1[i][k] * matrix2[k][j]
            }
        }
    }

    return result
}

fun main() {
    val matrix1 = arrayOf(
        doubleArrayOf(1.0, 2.0, 3.0),
        doubleArrayOf(4.0, 5.0, 6.0),
        doubleArrayOf(7.0, 8.0, 9.0)
    )

    val matrix2 = arrayOf(
        doubleArrayOf(4.0, 6.0),
        doubleArrayOf(7.0, 3.0),
        doubleArrayOf(1.0, 2.0)
    )

    try {
        val mul = multiplyMatrices(matrix1, matrix2)

        mul.forEach { row -> println(row.joinToString(" ")) }
    } catch (e: IllegalArgumentException) {
        println(e.message)
    }
}
 
    
/*
run:
 
21.0 18.0
57.0 51.0
93.0 84.0

*/

 



answered Mar 4, 2025 by avibootz
...