代码之家  ›  专栏  ›  技术社区  ›  NLed

转置矩阵

  •  1
  • NLed  · 技术社区  · 14 年前

    我想转换一个矩阵,这是一个非常简单的任务,但它不适合我:

    更新

    我正在调换第一个矩阵 把它放在第二个里面 两个 数组指向同一结构 我 需要两个数组(目标和源) 所以我可以在以后展示 比较。

    struct testing{
      int colmat1;
      int rowmat1;
      float mat[64][64];
    };
    
    int testtranspose(testing *test,testing *test2){
      int i,j;
      test2->colmat1 = test->rowmat1;
      test2->rowmat1 = test->colmat1
      for(i=0;i<test->rowmat1;i++){
        for(j=0;j<test->colmat1;j++){
          test2->mat[i][j] = test->mat[i][j];
        }
        printf("\n");
      }
    }
    

    我认为这是正确的方法,但显然对于如下矩阵:

    1 2
    3 4
    5 6
    7 8
    

    我得到:

    1 2 0 0
    3 4 0 0
    

    怎么了?

    请帮忙, 谢谢!

    3 回复  |  直到 14 年前
        1
  •  4
  •   interjay    14 年前

    要转换矩阵,需要更改行和列。所以你需要使用:

    targetMatrix[i][j] = sourceMatrix[j][i];
    

    注意i,j的顺序是如何改变的,因为一个矩阵的行是另一个矩阵的列。

    顺便说一下,而不是 (*a).b ,你可以写 a->b . 这是访问结构指针字段的常规方法。

        2
  •  2
  •   Jujjuru    14 年前

    试试这个…

       struct testing{
      int colmat;
      int rowmat;
      float mat[64][64];
    };
    
    int testtranspose(testing *test,testing *test2){
      int i,j;
      test2->colmat = test->rowmat;
      test2->rowmat = test->colmat;
      for(i=0;i<test->rowmat;i++){
        for(j=0;j<test->colmat;j++){
          test2->mat[j][i] = test->mat[i][j];
        }
      }
      return 0;
    }
    int printmat(testing* mat)
    {
        for(int i=0;i<mat->rowmat;i++)
        {
            printf("\n");
            for(int j=0;j<mat->colmat;j++)
                printf(("  %f"),mat->mat[i][j]);
        }
        return 0;
    }
    
                // 2
    // main.cpp
    int _tmain(int argc, _TCHAR* argv[])
    {
        testing mat1, mat2;
        memset(&mat1,0,sizeof(testing));
        memset(&mat2,0,sizeof(testing));
        mat1.colmat =2;
        mat1.rowmat =3;
        for(int i=0;i<mat1.rowmat;i++)
        {
            for(int j=0;j<mat1.colmat;j++)
                mat1.mat[i][j] = (float)rand();
        }
        printmat(&mat1);
        testtranspose(&mat1,&mat2);
        printmat(&mat2);
        getchar();
    
    }
    
        3
  •  0
  •   moldovean    10 年前

    我是新的C/C++(第三天左右:)),我也有同样的问题。我的方法稍有不同,因为我认为有一个函数可以返回一个转置矩阵是很好的。不幸的是,正如我发现的,您不能返回数组,也不能将数组传递给C++中的函数(更不用说是双数组),但是您可以传递/返回一个与数组类似的指针。我就是这么做的:

    int * matrix_transpose(int * A, int A_rows, int A_cols){
        int * B;
        int B_rows, B_cols;
        B_rows = A_cols; B_cols= A_rows;
        B = new int [B_rows*B_cols];
        for(int i=0;i<B_rows;i++){
            for(int j=0;j<B_cols;j++){
                B[i*B_cols+j]=A[j*A_cols+i];
            }
        }
        return B;
    };
    

    诀窍在于动态数组。我使用a_行和b_行作为单独的名称(您只能使用行和列),以便在读取代码时减少问题的复杂性和混乱性。

    B = new int [rows*cols] // This is cool in C++.