矩阵的转置是将行交换为列的过程。对于2x3
矩阵,
Matrix
a11 a12 a13
a21 a22 a23
Transposed Matrix
a11 a21
a12 a22
a13 a23
示例:查找矩阵转置的程序
public class Transpose {
public static void main(String[] args) {
int row = 2, column = 3;
int[][] matrix = { {2, 3, 4}, {5, 6, 4} };
// Display current matrix
display(matrix);
// Transpose the matrix
int[][] transpose = new int[column][row];
for(int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
transpose[j][i] = matrix[i][j];
}
}
// Display transposed matrix
display(transpose);
}
public static void display(int[][] matrix) {
System.out.println("The matrix is: ");
for(int[] row : matrix) {
for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
}
}
输出
The matrix is:
2 3 4
5 6 4
The matrix is:
2 5
3 6
4 4
在上面的程序中, display()
函数仅用于将矩阵的内容打印到屏幕上。
在此,给定矩阵的形式为2x3
,即row = 2
和column = 3
。
对于转置矩阵,我们将转置顺序更改为3x2
,即row = 3
和column = 2
。因此,我们有transpose = int[column][row]
矩阵的转置是通过简单地将列交换为行来计算的:
transpose[j][i] = matrix[i][j];