1import java.util.Scanner;
2public class MatrixTransposeInJava
3{
4 public static void main(String[] args)
5 {
6 int[][] arrGiven = {{2,4,6},{8,1,3},{5,7,9}};
7 // another matrix to store transpose of matrix
8 int[][] arrTranspose = new int[3][3];
9 // transpose matrix code
10 for(int a = 0; a < 3; a++)
11 {
12 for(int b = 0; b < 3; b++)
13 {
14 arrTranspose[a][b] = arrGiven[b][a];
15 }
16 }
17 System.out.println("Before matrix transpose: ");
18 for(int a = 0; a < 3; a++)
19 {
20 for(int b = 0; b < 3; b++)
21 {
22 System.out.print(arrGiven[a][b] + " ");
23 }
24 System.out.println();
25 }
26 System.out.println("After matrix transpose: ");
27 for(int a = 0; a < 3; a++)
28 {
29 for(int b = 0; b < 3; b++)
30 {
31 System.out.print(arrTranspose[a][b] + " ");
32 }
33 System.out.println();
34 }
35 }
36}
1 //Transpose a Matrix
2
3 for (int row = 0; row < matrix.length; row++) {
4
5 for (int col = row; row < matrix[row].length; col++)
6 {
7 // Swap
8 int data = matrix[row][col];
9 matrix[row][col] = matrix[col][row];
10 matrix[col][row] = data;
11 }
12
13 }
1for (int row = 0; row < matrix.length; row++) {
2
3 for (int col = row; col < matrix[row].length; col++)
4 {
5 // Swap
6 int data = matrix[row][col];
7 matrix[row][col] = matrix[col][row];
8 matrix[col][row] = data;
9 }
10
11 }