Search code examples
c++eigenrcpp

How do I swap both columns and rows in a symmetrical sparse matrix in C++'s Eigen?


I am trying achieve the following dense matrix operation for a sparse symmetrical matrix:

    dm.col(j).swap(dm.col(i));
    dm.row(j).swap(dm.row(i));

In order to interchange two columns (and rows) in a sparse symmetric matrix, I am trying to generate a permutation matrix so that I can pass it to .twistedBy():

    Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> P;
    P.setIdentity();
    P.col(j).swap(P.col(i));

    sm = sm.twistedBy(P);

Unfortunately, .col().swap() is not supported for permutation matrices. What should I do?

This question clarifies the use of .twistedBy, but does not explain how to construct a permutation matrix: Permuting sparse matrices in Eigen

I am having a hard time trying to understand the documentation of eigen: https://eigen.tuxfamily.org/dox/classEigen_1_1PermutationMatrix.html

Any general help with that would be appreciated, too!

Thank you for your time!


Solution

  • You are looking for applyTranspositionOnTheRight:

    Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic >::PermutationMatrix P(n);
    P.setIdentity();
    P.applyTranspositionOnTheRight(j, i);