如何使用 C 程序计算矩阵的转置?
矩阵的转置
矩阵的转置是其行是原矩阵的列,即如果A和B是两个矩阵,使得矩阵B的行是矩阵A的列,那么矩阵B被称为矩阵A的转置。
用于将矩阵m(i,j)更改为m(j,i)的逻辑如下 -
for (i = 0;i < m;i++) for (j = 0; j < n; j++) transpose[j][i] = matrix[i][j];
程序 1
在本示例中,我们将使用 for 循环来打印矩阵的转置。
#include <stdio.h> int main(){ int m, n, i, j, matrix[10][10], transpose[10][10]; printf("Enter rows and columns :
"); scanf("%d%d", &m, &n); printf("Enter elements of the matrix
"); for (i= 0; i < m; i++) for (j = 0; j < n; j++) scanf("%d", &matrix[i][j]); for (i = 0;i < m;i++) for (j = 0; j < n; j++) transpose[j][i] = matrix[i][j]; printf("Transpose of the matrix:
"); for (i = 0; i< n; i++) { for (j = 0; j < m; j++) printf("%d\t", transpose[i][j]); printf("
"); } return 0; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
Enter rows and columns : 2 3 Enter elements of the matrix 1 2 3 2 4 5 Transpose of the matrix: 1 2 2 4 3 5
程序 2
#include<stdio.h> #define ROW 2 #define COL 5 int main(){ int i, j, mat[ROW][COL], trans[COL][ROW]; printf("Enter matrix:
"); // input matrix for(i = 0; i < ROW; i++){ for(j = 0; j < COL; j++){ scanf("%d", &mat[i][j]); } } // create transpose for(i = 0; i < ROW; i++){ for(j = 0; j < COL; j++){ trans[j][i] = mat[i][j]; } } printf("
Transpose matrix:
"); // print transpose for(i = 0; i < COL; i++){ for(j = 0; j < ROW; j++){ printf("%d ", trans[i][j]); } printf("
"); } return 0; }
输出
Enter matrix: 1 2 3 4 5 5 4 3 2 1 Transpose matrix: 1 5 2 4 3 3 4 2 5 1
广告