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,
- Define Matrices: Two matrices
matrix1
andmatrix2
are defined using nested arrays. These matrices are 2×3 matrices (2 rows and 3 columns). - Perform Matrix Subtraction:
- A new matrix
resultMatrix
is created using theArray
constructor with the same dimensions asmatrix1
. - The elements of
resultMatrix
are calculated by subtracting the corresponding elements ofmatrix1
andmatrix2
.
- A new matrix
- 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.