设计一个函数,将一个m*n的二维矩阵的行与列的元素互换
时间: 2024-05-15 18:19:34 浏览: 99
以下是Python代码实现:
```python
def transpose_matrix(matrix):
m = len(matrix)
n = len(matrix[0])
transposed_matrix = [[0 for i in range(m)] for j in range(n)]
for i in range(m):
for j in range(n):
transposed_matrix[j][i] = matrix[i][j]
return transposed_matrix
```
该函数接受一个二维矩阵作为参数,并返回一个新的矩阵,新矩阵的行与列元素互换。在函数中,我们首先获取原矩阵的行数m和列数n,然后创建一个新矩阵transposed_matrix,其行数为n,列数为m。接下来,我们使用两个嵌套的循环遍历原矩阵中的所有元素,并将其赋值给新矩阵的相应位置。最后返回新矩阵即可。
相关问题
python设计一个函数,将一个m*n的二维矩阵的行与列的元素互换
def transpose(matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
m = len(matrix)
n = len(matrix[0])
result = [[0] * m for _ in range(n)]
for i in range(m):
for j in range(n):
result[j][i] = matrix[i][j]
return result
# example
matrix = [[1, 2, 3], [4, 5, 6]]
print(transpose(matrix)) # [[1, 4], [2, 5], [3, 6]]
将一个二维数组行和列元素互换,存到另一个二维数组中并输出这两个矩阵。
好的,我来为您解答这个问题。下面是示例代码:
```c
#include <stdio.h>
#define ROW 3
#define COL 4
void transpose(int arr1[][COL], int arr2[][ROW]) {
int i, j;
for(i = 0; i < ROW; ++i) {
for(j = 0; j < COL; ++j) {
arr2[j][i] = arr1[i][j];
}
}
}
void printArray(int arr[][COL], int row, int col) {
int i, j;
for(i = 0; i < row; ++i) {
for(j = 0; j < col; ++j) {
printf("%d\t", arr[i][j]);
}
printf("\n");
}
}
int main() {
int arr1[ROW][COL] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int arr2[COL][ROW];
transpose(arr1, arr2);
printf("Original matrix:\n");
printArray(arr1, ROW, COL);
printf("Transposed matrix:\n");
printArray(arr2, COL, ROW);
return 0;
}
```
首先定义了两个二维数组,arr1 和 arr2,分别表示原始矩阵和转置后的矩阵。然后我们定义了一个 transpose 函数,用于实现矩阵转置操作。在这个函数中,我们使用两个嵌套的循环,遍历原始矩阵的每一个元素,并将其按照行列互换的方式存储到转置后的矩阵中。最后,我们定义了一个 printArray 函数,用于输出数组的元素。在主函数中,我们先输出原始矩阵,再输出转置后的矩阵。
阅读全文
相关推荐













