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

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)

Java Reader/Writer

Java Other Topics

Java Program to Find Matrix Transpose

Comprehensive Java Examples

In this program, you will learn to find and print the transpose of a given matrix in Java.

The transpose of a matrix is the process of exchanging rows with columns. For2x3matrix,

matrix
a11    a12    a13
a21    a22    a23
Transpose Matrix
a11    a21
a12    a22
a13    a23

Example: Program to find matrix transpose

public class Transpose {
    public static void main(String[] args) {
        int row = 2, column = 3;
        int[][] matrix = { {2, 3, 4}, {5, 6, 4};
        //Display the current matrix
        display(matrix);
        //Transpose Matrix
        int[][] transpose = new int[column][row];
        for (int i = 0; i < row;++) {
            for (int j = 0; j < column;++) {
                transpose[j][i] = matrix[i][j];
            }
        }
        //Display Transpose Matrix
        display(transpose);}}
    }
    public static void display(int[][] matrix) {
        System.out.println("The matrix is: ");
        for (int[] row : matrix) {
            for (int column : row) {
                System.out.print(column + "    ");
            }
            System.out.println();
        }
    }
}

When the program is run, the output is:

The matrix is:
2    3    4    
5    6    4    
The matrix is:
2    5    
3    6    
4    4

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

Here, the given matrix is in the form of2x3which means row = 2 and column = 3.

For the transpose matrix, we change the transpose order to3x2, which means row = 3 and column = 2. Therefore, we have transpose = int[column][row]

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

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

Comprehensive Java Examples