from today to future, I will try my best to study and practice

Sparse Matrix's Transpose

Sparse Matrix

Usually, suppose that there is m rows and n cols, and t non-zero element in a matrix. Make δ=t/(mn), δ is called sparse factor. If δ0.05, we could call the matrix a sparse matrix.

Transpose Algorithm

  • The data is ordered by row.

About classical method:

  • According to matrix’s diagonal, making half of number of all element( munu) tranpose is a easy way to realize matrix’s transpose.

    Time Complexity: O(munu)

There are two methods.
  • First

    The result must orderly by col. If don’t require the result is orderly, We could do this in time O(nu).

    From first row, find the elem whose row-num(i) is this row, and transpose to col.

    // M is source Matrix, T is target Matrix
    // mu is row-num, nu is col-num, tu is non-zero-num
    // .i is row, .j is col, .e is elem
    Status TranposeMatrix(Matrix M, Matrix &T) { =, = m.Mu, T.tu = M.tu;
        if ( {
            q = 1;
            for(col = 1; col <=; ++col)
            for(p = 1; p <= M.tu; ++p) 
                if([p].j == col) {
          [q].i =[p].i;
          [q].j =[p].j;
          [q].e =[p].e;
        return OK;

    Obviously, there is nutu times operation.

    Time Complexity: O(nutu)

    If tumu, this method is bad.

  • second

    Name: Fast Transpose

    If we could determine every col of result serial number, we could make every data right location.

    cpot[1] = 1;
    cpot[col] = cpot[col- 1] + num[col- 1];

    Because the source data is ordered by row, we could make every col a point to mark this col’s the data sequence.

    Status FastTransposeMatrix(Matrix M, Matrix &T) { =; =; T.tu = M.tu;
        if(T.tu) {
            for(col = 1; col <=; ++col) num[col] = 0;
            for(t = 1; t <= M.tu; ++t) ++num[[t].j];
            cpot[i] = 1;
            for (col = 2; col <=; ++col) cpot[col] = cpot[col - 1] + num [col - 1];
            for (p= 1; p<= M.tu; ++p) {
                col =[p].j;
                q = cpot[col];
      [q].i =[p].j;
      [q].j =[p].i;
      [q].e =[p].e;
                ++ cpot[col];

    Obviously, there is nu+tu times operation.

    Time Complexity: O(nu+tu)

    In worst situation, tu=munu, this time is O(munu), it still works well.

个人分类: 矩阵
想对作者说点什么? 我来说一句