Write a Java Program to Find Transpose of a Matrix

As a Java programmer, you may come across the need to find the transpose of a matrix.

In simple terms, a transpose of a matrix is a matrix obtained by interchanging rows and columns of the original matrix.

For example, if we have a matrix A of size m x n, its transpose A’ will be of size n x m.

In this tutorial, we will learn how to write a Java program to find the transpose of a matrix.


First, let’s understand the logic behind finding the transpose of a matrix.

To find the transpose of a matrix, we need to loop through the rows and columns of the original matrix and interchange their values.

We can create a new matrix to store the transpose of the original matrix or we can modify the original matrix itself to obtain the transpose.

Now, let’s see how we can implement the above logic in Java.

We will use a nested for loop to iterate through the rows and columns of the matrix.

We will then swap the values of the current element with the element at its corresponding position in the transpose matrix.

Here’s the Java program to find the transpose of a matrix:

public class TransposeMatrix {
   public static void main(String[] args) {
      int rows = 3, columns = 3;
      int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
      int[][] transpose = new int[columns][rows];

      // Finding transpose of matrix
      for(int i = 0; i < rows; i++) {
         for (int j = 0; j < columns; j++) {
            transpose[j][i] = matrix[i][j];
         }
      }

      // Displaying the original matrix
      System.out.println("Original matrix: ");
      for(int i = 0; i < rows; i++) {
         for (int j = 0; j < columns; j++) {
            System.out.print(matrix[i][j] + " ");
         }
         System.out.println();
      }

      // Displaying the transpose matrix
      System.out.println("Transpose of matrix: ");
      for(int i = 0; i < columns; i++) {
         for (int j = 0; j < rows; j++) {
            System.out.print(transpose[i][j] + " ");
         }
         System.out.println();
      }
   }
}

In this program, we first declare the size of the matrix and initialize it with some values.

We then declare a new matrix to store the transpose of the original matrix.

We use nested for loops to iterate through the rows and columns of the original matrix and swap the values of the current element with the element at its corresponding position in the transpose matrix.

Finally, we display both the original matrix and the transpose matrix using another set of nested for loops.

That’s it!

With this Java program, you can easily find the transpose of any matrix.

I hope you found this tutorial post helpful.