You are here

Java program to transpose a matrix

Java program to find transpose of a matrix of any order.

Java programming source code

  1. import java.util.Scanner;
  2.  
  3. class TransposeAMatrix
  4. {
  5.    public static void main(String args[])
  6.    {
  7.       int m, n, c, d;
  8.  
  9.       Scanner in = new Scanner(System.in);
  10.       System.out.println("Enter the number of rows and columns of matrix");
  11.       m = in.nextInt();
  12.       n = in.nextInt();
  13.  
  14.       int matrix[][] = new int[m][n];
  15.      
  16.       System.out.println("Enter the elements of matrix");
  17.  
  18.       for (c = 0; c < m; c++)
  19.          for (d = 0; d < n; d++)
  20.             matrix[c][d] = in.nextInt();
  21.  
  22.       int transpose[][] = new int[n][m];
  23.      
  24.       for (c = 0; c < m; c++)
  25.          for (d = 0; d < n; d++)              
  26.             transpose[d][c] = matrix[c][d];
  27.  
  28.       System.out.println("Transpose of the matrix:");
  29.  
  30.       for (c = 0; c < n; c++)
  31.       {
  32.          for (d = 0; d < m; d++)
  33.                System.out.print(transpose[c][d]+"\t");
  34.  
  35.          System.out.print("\n");
  36.       }
  37.    }
  38. }

Download Transpose matrix program class file.

Output of program:
Transpose matrix Java program output

This code can be used to check if a matrix is symmetric or not, just compare the matrix with it's transpose, if they are the same then it's symmetric otherwise non symmetric, also it's useful for calculating orthogonality of a matrix.