矩阵转置的原理:行元素变成列元素,列元素变成行元素
例如:

矩阵转置代码
- #include
- #include
- #include
- #include
-
- //矩阵转置
- double** Matrix_T(double** arr)
- {
- if(arr==NULL)exit(-1);
- int row = (int)_msize(arr) / (int)sizeof(double*);
- int col = (int)_msize(*arr) / (int)sizeof(double);
- double** T = (double**)malloc(sizeof(double*) * col);
- int i = 0;
- int j = 0;
- if (T != NULL)
- {
- for (i = 0; i < col; i++)
- {
- T[i] = (double*)malloc(sizeof(double) * row);
- }
- }
- for (i = 0; i < col; i++)
- {
- for (j = 0; j < row; j++)
- {
- T[i][j] = arr[j][i];
- }
- }
- return T;
- }
上述代码中:
上述方法使用的是malloc开辟的矩阵,该方法相对于用二维数组存储矩阵有以下几种优势:
1)函数传参时不用输入行列,只需传入指针
2)矩阵的大小可以未知,矩阵维数可以更改
3)不需要宏定义,程序可移植性高
malloc开辟矩阵的代码如下:
- double** Make_Matrix(int row, int col)
- {
- int i, j;
- double** arr = (double**)malloc(sizeof(double*) * row);
- if (arr != NULL)
- {
- for (i = 0; i < row; i++)
- {
- arr[i] = (double*)malloc(sizeof(double) * col);
- }
- }
- return arr;
- }
该方法在C语言malloc开辟矩阵中有详细介绍。
测试:
为了方便测试,再加入初始化矩阵和打印矩阵两个函数
初始化函数
- void Init_Matrix(double** arr)
- {
- int i, j;
- int row = (int)_msize(arr) / (int)sizeof(double*);
- int col = (int)_msize(*arr) / (int)sizeof(double);
- for (i = 0; i < row; i++)
- {
- for (j = 0; j < col; j++)
- {
- arr[i][j] = pow(i,j);
- }
- }
- }
为了更加直观,让每个元素等于 i 的 j 次方
打印函数
- //打印矩阵
- void print(double** arr)
- {
- putchar('\n');
- int i, j, row, col;
- row = (int)_msize(arr) / (int)sizeof(double*);
- col = (int)_msize(*arr) / (int)sizeof(double);
- for (i = 0; i < row; i++)
- {
- for (j = 0; j < col; j++)
- {
- printf("%8.3lf ", arr[i][j]);
- }
- putchar('\n');
- }
- }
主函数测试
- int main()
- {
- int i = 3;
- int j = 5;
- double** arr = Make_Matrix(i, j);
- Init_Matrix(arr);
- double** res = Matrix_T(arr);
- printf("原矩阵:>");
- print(arr);
- printf("逆矩阵:>");
- print(res);
- return 0;
- }
