C++矩阵求转置矩阵
来源:互联网 发布:房子平面设计软件手机 编辑:程序博客网 时间:2024/06/08 08:03
n阶矩阵求转置,也就是沿着左对角线反转矩阵;a[i][j] 与 a[j][i] 对换。
算法实现:
#include<iostream>using namespace std;template<class T>void swap(T* a, T* b){T temp = a;*a = *b;*b = temp;return;}template<class T>void transpose(T& a, int rows){for (int i = 0; i < rows; i++){for (int j = i + 1; j < rows; j++){swap(a[i][j], a[j][i]);}}return;}int main(){int a[3][3] = { 1,2,3,4,5,6,7,8,9 };for (int i = 0; i < 3; i++){for (int j = 0; j < 3; j++){cout << a[i][j] << " ";}cout << endl;}transpose(a, 3);for (int i = 0; i < 3; i++){for (int j = 0; j < 3; j++){cout << a[i][j] << " ";}cout << endl;}return 0;}n * m矩阵的转置,行和列颠倒。
算法实现:
#include<iostream>using namespace std;template<class T>void swap(T* a, T* b){T temp = a;*a = *b;*b = temp;return;}template<class T,class T1>void transpose(T& a, T1& b,int rows,int cols){for (int i = 0; i < rows; i++){for (int j = 0; j < cols; j++){b[j][i] = a[i][j];}}return;}int main(){int a[4][3] = { 1,2,3,4,5,6,1,2,3,4,5,6 };int b[3][4] = { 0 };for (int i = 0; i < 4; i++){for (int j = 0; j < 3; j++){cout << a[i][j] << " ";}cout << endl;}cout << endl;transpose(a,b,4,3);for (int i = 0; i < 3; i++){for (int j = 0; j < 4; j++){cout << b[i][j] << " ";}cout << endl;}return 0;}
阅读全文
0 0