C++n阶矩阵求转置矩阵的算法实现
程序员文章站
2023-01-11 21:56:10
n阶矩阵求转置,也就是沿着左对角线反转矩阵;a[i][j] 与 a[j][i] 对换。
算法实现:
#include
using namespace std;
temp...
n阶矩阵求转置,也就是沿着左对角线反转矩阵;a[i][j] 与 a[j][i] 对换。
算法实现:
#include using namespace std; template void swap(T* a, T* b) { T temp = a; *a = *b; *b = temp; return; } template 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 using namespace std; template void swap(T* a, T* b) { T temp = a; *a = *b; *b = temp; return; } template 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; }