【问题标题】:Permuting sparse matrices in Eigen在 Eigen 中置换稀疏矩阵
【发布时间】:2015-01-10 19:04:18
【问题描述】:

我想置换 Eigen 中稀疏矩阵的行和列。这是我的代码,但它不起作用。

#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;
}

它置换行和置换列,但它不会同时进行。有谁知道如何排列列和行?

谢谢。

【问题讨论】:

    标签: matrix permutation eigen sparse-matrix


    【解决方案1】:

    如果要应用对称排列P * Y * P^-1,那么最好使用twistedBy 方法:

    SpMat z = y.twistedBy(perm);
    

    否则你必须先申请一个,然后再申请另一个:

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

    【讨论】:

    • 谢谢。我想要的是应用对称排列。但问题是我最终得到Eigen::SparseSymmetricPermutationProduct&lt;SpMat, 3&gt; z = y.twistedBy(perm);。你知道我如何修改 y 以使其置换吗?或者如果我不能修改 y 本身,我如何获得置换后的 y。
    • 我想通了。您可以创建一个新变量,然后使用 evalTo:SpMat k; z.evalTo(k)。我想知道如果我这样做z.evalTo(y) 是否会有任何错误。以及这些操作在时间和内存方面的效率如何。谢谢。
    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多