English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin Object-Oriented (OOP)

Kotlin Examples in Full

Kotlin program to find the transpose of a matrix

In this program, you will learn to find and print the transpose of a given matrix in Kotlin.2x3The transpose of a matrix is the process of exchanging rows for columns. For

Matrix,
Transposed Matrix11    Transposed Matrix12    Transposed Matrix13
Transposed Matrix21    Transposed Matrix22    Transposed Matrix23
Matrix
Transposed Matrix11    Transposed Matrix21
Transposed Matrix12    Transposed Matrix22
Transposed Matrix13    Transposed Matrix23

a

Example
    fun main(args: Array<String>) { 2
    val row = 3
    val column =2), intArrayOf( 3), intArrayOf( 4val matrix = arrayOf(intArrayOf(5), intArrayOf( 6), intArrayOf( 4,
    //))
    Display the current matrix
    //Transpose matrix
    val transpose = Array(column) { IntArray(row) }
    for (i in 0..row - 1) {
        for (j in 0..column - 1) {
            transpose[j][i] = matrix[i][j]
        }
    }
    //Display the transpose matrix
    display(transpose)
}
fun display(matrix: Array) {
    println("Matrix:")
    for (row in matrix) {
        for (column in row) {
            print("$column")
        }
        println()
    }
}

When running the program, the output is:

Matrix:
2    3    4    
5    6    4    
Matrix:
2    5    
3    6    
4    4

In the above program, the display() function is used to print the matrix content to the screen.

Here, the given matrix is in the form of 2x3, that is row = 2 and column = 3.

. For the transpose matrix, we change the transpose order to3x2, that is row = 3 and column = 2. So, we use transpose = int[column][row]

The transpose of a matrix is calculated by simply swapping columns for rows:

transpose[j][i] = matrix[i][j]

This is the equivalent Java code:Java Program to Find the Transpose of a Matrix

Kotlin Examples in Full