设计一个子函数,将任意n×n的矩阵转置,并在主函数中调用此函数将一个4×4的矩阵转置,并在主函数中输出结果。
时间: 2023-06-26 08:06:16 浏览: 94
以下是一个实现矩阵转置的示例代码:
```python
def transpose_matrix(matrix):
n = len(matrix)
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# 测试代码
matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
transpose_matrix(matrix)
for row in matrix:
print(row)
```
输出:
```
[1, 5, 9, 13]
[2, 6, 10, 14]
[3, 7, 11, 15]
[4, 8, 12, 16]
```
在主函数中调用此函数并输出结果:
```python
matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
transpose_matrix(matrix)
for row in matrix:
print(row)
```
输出:
```
[1, 5, 9, 13]
[2, 6, 10, 14]
[3, 7, 11, 15]
[4, 8, 12, 16]
```
阅读全文