Sparse matrix storage in C

前端 未结 3 1978
逝去的感伤
逝去的感伤 2021-01-15 11:42

I have a sparse matrix that is not symmetric I.E. the sparsity is somewhat random, and I can\'t count on all the values being a set distance away from the diagonal.

3条回答
  •  旧巷少年郎
    2021-01-15 12:15

    Derek, you mentioned in one of the comments that you want to use a single malloc. That means that you know how many nonempty elements you have. Given this, tt is possible to store the sparse matrix in an array which holds, per element, the value of the matrix element and the "location delta" to the next element. Something like:

    struct melem {
        int value; // value of data
        int offset; // offset to next element
    }
    
    struct melem matrix[num_nonempty_elements];
    
    ...
    
    // Note: this is pseudocode!
    matrix[row*COLS + col].value = a[row][col];
    matrix[row*COLS + col].offset = (row*COLS + col)_[i] - (row*COLS + col)_[i-1];
    

    EDIT: Thinking about it, this is pretty similar to the linked list approach, but requires 1 allocation. OTOH, it may require more calculation to access the required cell.

提交回复
热议问题