使用 Java 函数计算给定矩阵的转置矩阵
在本程序中,您将学习在 Java 中查找和打印给定矩阵的转置。
要理解此示例,您应该具备以下 Java 编程的知识:
矩阵的转置是将行交换为列的过程。对于 2x3
矩阵,
a11 a12 a13
a21 a22 a23
它的转置矩阵未:
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];