Kotlin – Matrix Addition

Kotlin – Matrix Addition

In Kotlin, matrix addition involves adding corresponding elements of two matrices to create a new matrix with the same dimensions.

Example

The following is a simple example of adding two matrices element-wise.

Kotlin Program

fun main() {
    // Define the matrices
    val matrix1 = arrayOf(
        intArrayOf(1, 2, 3),
        intArrayOf(4, 5, 6)
    )
    val matrix2 = arrayOf(
        intArrayOf(7, 8, 9),
        intArrayOf(10, 11, 12)
    )

    // Perform matrix addition
    val resultMatrix = Array(matrix1.size) { i ->
        IntArray(matrix1[0].size) { j ->
            matrix1[i][j] + matrix2[i][j]
        }
    }

    // Print the result matrix
    for (row in resultMatrix) {
        for (element in row) {
            print("$element ")
        }
        println()
    }
}

Output

8 10 12 
14 16 18 

In the program,

  1. Define Matrices: Two matrices matrix1 and matrix2 are defined using nested arrays. These matrices are 2×3 matrices (2 rows and 3 columns).
  2. Perform Matrix Addition:
    • A new matrix resultMatrix is created using the Array constructor with the same dimensions as matrix1.
    • The elements of resultMatrix are calculated by adding the corresponding elements of matrix1 and matrix2.
  3. Print Result:
    • The result matrix is printed using nested loops. Each element of the result matrix is printed, and a newline is added after each row.

We have used nested for loop to iterate over the elements in all the rows of the two matrices.

References

Summary

Matrix addition in Kotlin is done by adding corresponding elements of two matrices to generate a new matrix with the same dimensions. It follows the basic mathematical principle of element-wise addition.