Kotlin – Matrix Subtraction

Kotlin – Matrix Subtraction

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

Example

Let’s write with a simple example of subtracting 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(1, 0, 1),
        intArrayOf(5, 1, 2)
    )

    // Perform matrix subtraction
    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

0 2 2 
-1 4 4 

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 Subtraction:
    • A new matrix resultMatrix is created using the Array constructor with the same dimensions as matrix1.
    • The elements of resultMatrix are calculated by subtracting 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

  • Matrix Subtraction by mathpi.net

Summary

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