• C语言——矩阵转置


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

    例如:

    \begin{bmatrix} 1 &2 &3 &4 \\ 5&6 &7 &8 \\ 9 &10 &11 &12 \end{bmatrix}\rightarrow \begin{bmatrix} 1 &5 &9 \\ 2&6 &10 \\ 3&7 &11 \\ 4&8 &12 \end{bmatrix}

    矩阵转置代码 

    1. #include
    2. #include
    3. #include
    4. #include
    5. //矩阵转置
    6. double** Matrix_T(double** arr)
    7. {
    8. if(arr==NULL)exit(-1);
    9. int row = (int)_msize(arr) / (int)sizeof(double*);
    10. int col = (int)_msize(*arr) / (int)sizeof(double);
    11. double** T = (double**)malloc(sizeof(double*) * col);
    12. int i = 0;
    13. int j = 0;
    14. if (T != NULL)
    15. {
    16. for (i = 0; i < col; i++)
    17. {
    18. T[i] = (double*)malloc(sizeof(double) * row);
    19. }
    20. }
    21. for (i = 0; i < col; i++)
    22. {
    23. for (j = 0; j < row; j++)
    24. {
    25. T[i][j] = arr[j][i];
    26. }
    27. }
    28. return T;
    29. }

    上述代码中:

    • 首先判断传入指针是否为空
    • 然后判断矩阵的维数,这部分在C语言判断矩阵维数中有详细讲解
    • 为转置后的矩阵开辟空间
    • 进行矩阵装置,行列互换传参 

    上述方法使用的是malloc开辟的矩阵,该方法相对于用二维数组存储矩阵有以下几种优势:

    1)函数传参时不用输入行列,只需传入指针

    2)矩阵的大小可以未知,矩阵维数可以更改

    3)不需要宏定义,程序可移植性高

    malloc开辟矩阵的代码如下:

    1. double** Make_Matrix(int row, int col)
    2. {
    3. int i, j;
    4. double** arr = (double**)malloc(sizeof(double*) * row);
    5. if (arr != NULL)
    6. {
    7. for (i = 0; i < row; i++)
    8. {
    9. arr[i] = (double*)malloc(sizeof(double) * col);
    10. }
    11. }
    12. return arr;
    13. }

    该方法在C语言malloc开辟矩阵中有详细介绍。 

    测试:

    为了方便测试,再加入初始化矩阵和打印矩阵两个函数

    初始化函数 

    1. void Init_Matrix(double** arr)
    2. {
    3. int i, j;
    4. int row = (int)_msize(arr) / (int)sizeof(double*);
    5. int col = (int)_msize(*arr) / (int)sizeof(double);
    6. for (i = 0; i < row; i++)
    7. {
    8. for (j = 0; j < col; j++)
    9. {
    10. arr[i][j] = pow(i,j);
    11. }
    12. }
    13. }

     为了更加直观,让每个元素等于 i 的 j 次方

    打印函数 

    1. //打印矩阵
    2. void print(double** arr)
    3. {
    4. putchar('\n');
    5. int i, j, row, col;
    6. row = (int)_msize(arr) / (int)sizeof(double*);
    7. col = (int)_msize(*arr) / (int)sizeof(double);
    8. for (i = 0; i < row; i++)
    9. {
    10. for (j = 0; j < col; j++)
    11. {
    12. printf("%8.3lf ", arr[i][j]);
    13. }
    14. putchar('\n');
    15. }
    16. }

    主函数测试 

    1. int main()
    2. {
    3. int i = 3;
    4. int j = 5;
    5. double** arr = Make_Matrix(i, j);
    6. Init_Matrix(arr);
    7. double** res = Matrix_T(arr);
    8. printf("原矩阵:>");
    9. print(arr);
    10. printf("逆矩阵:>");
    11. print(res);
    12. return 0;
    13. }

  • 相关阅读:
    经典算法之冒泡排序
    Linux工具——gdb
    【Electron】vue+electron快捷键设置
    集合 set
    美团前端vue面试题(边面边更)
    python3+requests+unittest实战详解(一)
    每日刷题记录 (九)
    Lambda 表达式怎么用?
    Leetode-891-子序列宽度之和
    一个简单的HTML网页 个人网站设计与实现 HTML+CSS+JavaScript自适应个人相册展示留言博客模板
  • 原文地址:https://blog.csdn.net/why1472587/article/details/128139326