java

Program to Find Transpose of a Matrix in Java

The transposed matrix is one whose rows are columns of the original matrix, i.e. if A and B are two matrices such that the rows of matrix B are the columns of matrix A then the matrix B is said to be transposed from matrix A.

To display the transposed matrix:

  1. Create an empty matrix.
  2. Copy the contents of the original matrix into the new matrix so that the elements in position [j] [i] of the original matrix should be copied to position [i] [j] of the new matrix.
  3. Display the new matrix.

 

 

Example: Transpose of a 2×2 Matrix
public class Main{
   public static void main(String args[]){
      int a[][]={{1,2},{3,4}};
      int b[][] = new int[2][2];

      System.out.println("Original matrix : ");
      for(int i = 0; i<2 ;i++){
         for(int j = 0; j<2 ;j++){
            System.out.print(a[i][j]+" ");
         }
         System.out.println();
      }

      System.out.println("Transposed matrix : ");
      for(int i = 0; i<2 ;i++){
         for(int j = 0; j<2 ;j++){
            b[i][j] = 0;
            for(int k = 0; k<2 ;k++){
               b[i][j] = a[j][i];
            }
            System.out.print(b[i][j]+" ");
         }
         System.out.println();
      }
   }
}

 
Output:

Original matrix :
1 2
3 4
Transposed matrix :
1 3
2 4
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *