java实现矩阵转置(附完整源码)
时间: 2023-11-11 08:03:24 浏览: 107
java实现矩阵转置
5星 · 资源好评率100%
以下是Java实现矩阵转置的完整源码:
```java
public class MatrixTranspose {
public static void main(String[] args) {
// 定义一个3行4列的矩阵
int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
// 输出原始矩阵
System.out.println("原始矩阵:");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
// 定义一个新矩阵用于存储转置后的矩阵
int[][] transposedMatrix = new int[matrix[0].length][matrix.length];
// 转置矩阵
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
transposedMatrix[j][i] = matrix[i][j];
}
}
// 输出转置后的矩阵
System.out.println("转置后的矩阵:");
for (int i = 0; i < transposedMatrix.length; i++) {
for (int j = 0; j < transposedMatrix[0].length; j++) {
System.out.print(transposedMatrix[i][j] + " ");
}
System.out.println();
}
}
}
```
运行结果如下:
```
原始矩阵:
1 2 3 4
5 6 7 8
9 10 11 12
转置后的矩阵:
1 5 9
2 6 10
3 7 11
4 8 12
```
阅读全文