📜  C程序来查找矩阵的转置

📅  最后修改于: 2021-05-28 04:13:40             🧑  作者: Mango

通过将行更改为列并将列更改为行来获得矩阵的转置。换句话说,通过将A [i] [j]更改为A [j] [i]可获得A [] []的转置。

矩阵转置

对于方矩阵:

下面的程序找到A [] []的转置并将结果存储在B [] []中,我们可以将N更改为不同的维数。

#include 
#define N 4
  
// This function stores transpose of A[][] in B[][]
void transpose(int A[][N], int B[][N])
{
    int i, j;
    for (i = 0; i < N; i++)
        for (j = 0; j < N; j++)
            B[i][j] = A[j][i];
}
  
int main()
{
    int A[N][N] = { {1, 1, 1, 1},
                    {2, 2, 2, 2},
                    {3, 3, 3, 3},
                    {4, 4, 4, 4}};
  
    int B[N][N], i, j;
  
    transpose(A, B);
  
    printf("Result matrix is \n");
    for (i = 0; i < N; i++)
    {
        for (j = 0; j < N; j++)
           printf("%d ", B[i][j]);
        printf("\n");
    }
  
    return 0;
}
输出:
Result matrix is 
1 2 3 4 
1 2 3 4 
1 2 3 4 
1 2 3 4

对于矩形矩阵:

下面的程序找到A [] []的转置,并将结果存储在B [] []中。

#include 
#define M 3
#define N 4
  
// This function stores transpose of A[][] in B[][]
void transpose(int A[][N], int B[][M])
{
    int i, j;
    for (i = 0; i < N; i++)
        for (j = 0; j < M; j++)
            B[i][j] = A[j][i];
}
  
int main()
{
    int A[M][N] = { {1, 1, 1, 1},
                    {2, 2, 2, 2},
                    {3, 3, 3, 3}};
  
    // Note dimensions of B[][]
    int B[N][M], i, j;
  
    transpose(A, B);
  
    printf("Result matrix is \n");
    for (i = 0; i < N; i++)
    {
        for (j = 0; j < M; j++)
        printf("%d ", B[i][j]);
        printf("\n");
    }
  
    return 0;
}
输出:
Result matrix is 
1 2 3 
1 2 3 
1 2 3 
1 2 3

就地矩阵

#include 
using namespace std;
  
#define N 4
  
// Converts A[][] to its transpose
void transpose(int A[][N])
{
    for (int i = 0; i < N; i++)
        for (int j = i+1; j < N; j++)
            swap(A[i][j], A[j][i]);
}
  
int main()
{
    int A[N][N] = { {1, 1, 1, 1},
                    {2, 2, 2, 2},
                    {3, 3, 3, 3},
                    {4, 4, 4, 4}};
  
    transpose(A);
  
    printf("Modified matrix is \n");
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
           printf("%d ", A[i][j]);
        printf("\n");
    }
  
    return 0;
}
输出:
Modified matrix is 
1 2 3 4 
1 2 3 4 
1 2 3 4 
1 2 3 4

请参考有关程序的完整文章以找到矩阵的转置,以获取更多详细信息!

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。