Transpose a Matrix in Java

Exercise:

Write a Java Program to transpose a matrix.

Click Here to View the Solution!
 public class TransposeMatrix {

 public static void main(String[] args) {
         int row = 3, column = 2;
         int[][] matrix = { {9,6}, {7, 8} , {5,4} };
  
         // Display given  matrix
         display(matrix);
  
         // Transpose the given upper matrix 
         int[][] transpose = new int[column][row];
         for(int i = 0; i < row; i++) {
             for (int j = 0; j < column; j++) {
                 transpose[j][i] = matrix[i][j];
             }
         }
         // Display transposed matrix on console screen
         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();
         }
     }
 } 
Click Here to View the Output!
The matrix is: 
 9    6    
 7    8    
 5    4    
 The matrix is: 
 9    7    5    
 6    8    4   
Click Here to View the Explanation!
  • In this program, the display() function is only used for printing the values contained in a matrix onto the console.
  • The matrix size that is being discussed here is of the size 3×2 i.e. it consists of 3 rows and 2 columns.
  • To perform transpose of any matrix, the order of the matrix is reversed which means for this case, the rows = 2 and columns = 3. Thus, a generic equation for the transpose becomes: transpose = int[column][row].
  • In simpler terms, swapping the number rows with the number of columns and vice versa gives us a matrix’s transpose: transpose[j][i] = matrix[i][j];