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