Search code examples
sparse-matrixeigen

Eigen - diagonal update of sparse matrix


What's the fastest way to edit the diagonal of a sparse matrix in Eigen? I've already filled it using triplets but I occasionally need to change all the diagonal values (they were already set to nonzero).


Solution

  • If acceptable, you could simply use their indices like

    sp_mat(i, i)
    

    As each access involves a binary search, the performance may not be satisfied. In this case, you could still achieve better performance with some restrictions.

    1. You don't change the underlying layout of the matrix, e.g. adding/deleting nnzs, compressing;
    2. You will access the diagonal repeatedly.

    With these restrictions, you could store the pointers of the diagonal components so that you can access the data later in O(1) time. You could get the pointer with

    &sp_mat(i, i)