Search code examples
matrixpermutationeigensparse-matrix

Permuting sparse matrices in Eigen


I want to permute the rows and columns of a sparse matrix in Eigen. Here's the code I have but it's not working.

#include <iostream>
#include <Eigen/Core>
#include <Eigen/SparseCore>
typedef Eigen::SparseMatrix<double> SpMat;
using namespace Eigen;
using namespace std;

int myrandom (int i) { return std::rand()%i;}
int main() {
    PermutationMatrix<Dynamic,Dynamic> perm(5);
    MatrixXd x = MatrixXd::Random(5,5);
    SpMat y = x.sparseView();
    int dim=5;
    perm.setIdentity();
    for (int i=dim-1; i>0; --i) {
        swap (perm.indices()[i],perm.indices()[myrandom(i+1)]);
    }
    cout << "permutation\n" << perm.indices() << endl << endl;
    cout << "original x\n" << y << endl << endl;
    cout << "permuted left x \n" << perm * y << endl << endl;
    cout << "permuted right x \n" << y * perm << endl << endl;
    cout << "permuted both x \n" << perm * y * perm << endl << endl;
}

It permutes the rows and permutes the columns, but it doesn't do both. Does anyone know how both the columns and rows can be permuted?

Thanks.


Solution

  • If you want to apply a symmetric permutation P * Y * P^-1, then the best is to use the twistedBy method:

    SpMat z = y.twistedBy(perm);
    

    otherwise you have to apply one and then the other:

    SpMAt z = (perm * y).eval() * perm;