二维数组矩阵转置
时间: 2023-07-03 11:22:44 浏览: 100
二维数组矩阵转置是指将原始矩阵的行和列交换得到一个新的矩阵,新矩阵的行数和列数与原始矩阵相反。下面是一个简单的实现代码:
```python
def transpose(matrix):
# 获取原始矩阵的行数和列数
rows = len(matrix)
cols = len(matrix[0])
# 创建一个新矩阵,行数和列数与原始矩阵相反
new_matrix = [[0 for _ in range(rows)] for _ in range(cols)]
# 遍历原始矩阵,将每个元素放入新矩阵对应的位置
for i in range(rows):
for j in range(cols):
new_matrix[j][i] = matrix[i][j]
return new_matrix
```
使用示例:
```python
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_matrix = transpose(matrix)
print(new_matrix)
# 输出:[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
```
注意:此代码只适用于二维数组的转置,如果需要处理更高维度的数组,可以考虑使用numpy库中的transpose函数。
相关问题
c语言二维数组矩阵转置
同样地,C语言中的二维数组矩阵转置也是将原始矩阵的行和列交换得到一个新的矩阵,新矩阵的行数和列数与原始矩阵相反。下面是一个简单的实现代码:
```c
#include <stdio.h>
void transpose(int matrix[][3], int rows, int cols) {
// 创建一个新矩阵,行数和列数与原始矩阵相反
int new_matrix[cols][rows];
// 遍历原始矩阵,将每个元素放入新矩阵对应的位置
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
new_matrix[j][i] = matrix[i][j];
}
}
// 将新矩阵的内容复制回原始矩阵
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
matrix[j][i] = new_matrix[i][j];
}
}
}
int main() {
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
printf("Original matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
transpose(matrix, 3, 3);
printf("Transposed matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
```
使用示例:
```c
Original matrix:
1 2 3
4 5 6
7 8 9
Transposed matrix:
1 4 7
2 5 8
3 6 9
```
注意:此代码只适用于二维数组的转置,如果需要处理更高维度的数组,可以考虑使用动态内存分配或第三方库等方式。
java二维数组矩阵转置
Java中二维数组矩阵转置的代码如下:
```java
public static int[][] transpose(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int[][] result = new int[n][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
result[j][i] = matrix[i][j];
}
}
return result;
}
```
阅读全文
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)