C++ 程序查找矩阵的转置
矩阵是以行和列形式排列的数字的矩形数组。矩阵的转置是一个新矩阵,其中原始矩阵的行现在是列,反之亦然。例如。
矩阵如下所示 −
1 2 3 4 5 6 7 8 9
上述矩阵的转置如下。
1 4 7 2 5 8 3 6 9
查找矩阵转置的程序如下 −
示例
#include<iostream<
using namespace std;
int main() {
int transpose[10][10], r=3, c=2, i, j;
int a[3][3] = { {1, 2} , {3, 4} , {5, 6} };
cout<<"The matrix is:"<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
for(i=0; i<r; ++i)
for(j=0; j<c; ++j) {
transpose[j][i] = a[i][j];
}
cout<<"The transpose of the matrix is:"<<endl;
for(i=0; i<c; ++i) {
for(j=0; j<r; ++j)
cout<<transpose[i][j]<<" ";
cout<<endl;
}
return 0;
}输出
The matrix is: 1 2 3 4 5 6 The transpose of the matrix is: 1 3 5 2 4 6
在上述程序中,矩阵已初始化。然后显示其值。这在以下代码段中显示。
int a[3][3] = { {1, 2} , {3, 4} , {5, 6} };
cout<<"The matrix is:"<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}使用嵌套 for 循环计算矩阵的转置。这如下所示。
for(i=0; i<r; ++i)
for(j=0; j<c; ++j) {
transpose[j][i] = a[i][j];
}最后,获取转置,并在屏幕上打印。这是通过以下代码段完成的。
cout<<"The transpose of the matrix is:"<<endl;
for(i=0; i<c; ++i) {
for(j=0; j<r; ++j)
cout<<transpose[i][j]<<" ";
cout<<endl;
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP