Write a Kotlin Program to Multiply two Matrices by Passing Matrix to a Function

In Kotlin, it is possible to multiply two matrices by passing them to a function.

This can be achieved by following a few steps.

Step 1: Define the Matrices

First, we need to define the matrices that we will be using in our program.

In this example, we will create two matrices, matrix1 and matrix2, and initialize them with some values.

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)
)

Step 2: Define the Function

Next, we need to define a function that will take in two matrices and return their product.

In Kotlin, we can define a function using the “fun” keyword, followed by the function name, and then the input parameters in parentheses.

We will call this function “matrixMultiplication”.

fun matrixMultiplication(matrix1: Array<IntArray>, matrix2: Array<IntArray>): Array<IntArray> {
val row1 = matrix1.size
val col1 = matrix1[0].size
val row2 = matrix2.size
val col2 = matrix2[0].size
if (col1 != row2) {
throw IllegalArgumentException("Cannot multiply matrices of incompatible sizes")
}
val result = Array(row1) { IntArray(col2) }
for (i in 0 until row1) {
for (j in 0 until col2) {
for (k in 0 until col1) {
result[i][j] += matrix1[i][k] * matrix2[k][j]
}
}
}
return result
}

Step 3: Call the Function

Finally, we need to call the function and pass in the two matrices that we defined earlier.

We will store the result of the function in a new matrix called “product”.

val product = matrixMultiplication(matrix1, matrix2)

Step 4: Print the Result

To see the result of the matrix multiplication, we can loop through the “product” matrix and print out each element.

for (i in 0 until product.size) {
for (j in 0 until product[0].size) {
print("${product[i][j]} ")
}
println()
}

The output of this program should be:

30 24 18
84 69 54
138 114 90

This is the result of multiplying the two matrices that we defined earlier.

By following these steps, we can easily multiply two matrices in Kotlin by passing them to a function.