transpose matrix code java code example
Example 1: in place transpose in a matrix in java
for (int row = 0; row < matrix.length; row++) {
for (int col = row; row < matrix[row].length; col++)
{
int data = matrix[row][col];
matrix[row][col] = matrix[col][row];
matrix[col][row] = data;
}
}
Example 2: java program to find transpose of a matrix
import java.util.Scanner;
public class MatrixTransposeInJava
{
public static void main(String[] args)
{
int[][] arrGiven = {{2,4,6},{8,1,3},{5,7,9}};
int[][] arrTranspose = new int[3][3];
for(int a = 0; a < 3; a++)
{
for(int b = 0; b < 3; b++)
{
arrTranspose[a][b] = arrGiven[b][a];
}
}
System.out.println("Before matrix transpose: ");
for(int a = 0; a < 3; a++)
{
for(int b = 0; b < 3; b++)
{
System.out.print(arrGiven[a][b] + " ");
}
System.out.println();
}
System.out.println("After matrix transpose: ");
for(int a = 0; a < 3; a++)
{
for(int b = 0; b < 3; b++)
{
System.out.print(arrTranspose[a][b] + " ");
}
System.out.println();
}
}
}