Kotlin Matrix Transpose

Matrix Transpose in Kotlin

In this tutorial, you will learn how to transpose a given matrix using Kotlin.

The transpose of a matrix is obtained by exchanging the rows and columns of the matrix.

In Kotlin, you can achieve matrix transposition by creating a new matrix and filling it with elements from the original matrix’s rows and columns. This process effectively flips the matrix along its main diagonal. We can use a for loop to iterate through the rows, and another for loop inside this for loop to iterate over the column data.

Example

Transposing a Matrix

We’ll start with an example of transposing a matrix:

In this example, the transposeMatrix() function transposes the given matrix by exchanging rows and columns. It creates a new matrix and assigns the elements accordingly.

Kotlin Program

// Function to transpose a matrix
fun transposeMatrix(matrix: Array<Array<Int>>): Array<Array<Int>> {
    val rows = matrix.size
    val columns = matrix[0].size
    val transposedMatrix = Array(columns) { Array(rows) { 0 } }

    for (i in 0 until rows) {
        for (j in 0 until columns) {
            transposedMatrix[j][i] = matrix[i][j]
        }
    }

    return transposedMatrix
}

fun main() {
    val originalMatrix = arrayOf(
        arrayOf(1, 2, 3),
        arrayOf(4, 5, 6),
        arrayOf(7, 8, 9)
    )

    val transposedMatrix = transposeMatrix(originalMatrix)

    println("Original Matrix:")
    for (row in originalMatrix) {
        println(row.contentToString())
    }

    println("Transposed Matrix:")
    for (row in transposedMatrix) {
        println(row.contentToString())
    }
}

Output

Original Matrix:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Transposed Matrix:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]

Summary

In this Kotlin Tutorial, we learned how to transpose a given matrix in Kotlin, with the help of example programs.