目录
实验原理:
矩阵转置是将一个矩阵的行和列互换得到的新矩阵。在二维数组中,可以通过两个for循环交换数组中每个元素的位置来实现矩阵转置。
实验思路:
首先定义一个大小为3x3的矩阵,然后输出矩阵的初始数据。接着使用两个for循环遍历矩阵,并通过交换矩阵中每个元素的位置实现矩阵转置。最后,再次遍历矩阵并输出转置后的矩阵。
实验代码:
下面是一个简单的 C++ 代码示例,可以将一个二维矩阵进行转置:
#include <iostream>
using namespace std;
const int SIZE = 3;
int main() {
int matrix[SIZE][SIZE] = {{1,2,3},{4,5,6},{7,8,9}};
int temp;
cout << "Before transpose:" << endl;
for(int i=0;i<SIZE;i++) {
for(int j=0;j<SIZE;j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
// Transpose the matrix
for(int i=0;i<SIZE;i++) {
for(int j=i;j<SIZE;j++) {
temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
cout << "After transpose:" << endl;
for(int i=0;i<SIZE;i++) {
for(int j=0;j<SIZE;j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
输出结果为:
Before transpose:
1 2 3
4 5 6
7 8 9
After transpose:
1 4 7
2 5 8
3 6 9