How to find a Transpose of a matrix by using java

In this program, we have solved the transpose of a matrix by using java. Here, the first question is coming in our mind that what is transpose. In the transpose process, we have interchanges the row of any matrix with columns & change the columns of the matrix with the row. Here we write the example of the transpose.

Matrix

a1  a2  a3
b1  b2  b3

Transpose of a matrix:

a1  b1
a2  b2
a3  b3

Java Program: Transpose of a matrix in Java

public class Main{

public static void main(String[] args) {
      int my_row = 2, my_column = 3;
     int[][] matrix = { {8, 9, 7}, {1, 2, 3} };
        // Display current matrix
        display(matrix);

        int[][] transpose = new int[my_column][my_row];
        for(int k = 0; k < my_row; k++) {
            for (int j = 0; j < my_column; j++) {
                transpose[j][k] = matrix[k][j];
            }
        }

        display(transpose);
    }

    public static void display(int[][] matrix) {
        System.out.println("The matrix is: ");
        for(int[] my_row : matrix) {
            for (int my_column : my_row) {
                System.out.print(my_column + "    ");
            }
            System.out.println();
        }
    }
}

 

In this program, we have created a matrix of  2 rows and 3 columns. We create a function for the display a matrix. we use nested loops for the transpose.
here first, we have declared a variable of row and column. After that, we started the procedure of a transpose & we use nested loops the first loop is for row and the second loop is for the column.

Syntax of a transpose of the matrix

Transpose[j][i]=Matrix[i][j]

The above line describes the logic of the transpose of the matrix. In this logic, we interchange the row with the column and interchange the column with the row.




The output of the program

The matrix is:                                                                                                                                       

8    9    7                                                                                                                                          

1    2    3                                                                                                                                          

The matrix is:                                                                                                                                       

8    1                                                                                                                                               

9    2                                                                                                                                               

7    3

Also, learn,


Leave a Reply

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