随机地用特征置换矩阵的行/列

sta*_*lax 5 c++ random permutation matrix eigen

我正在使用Eigen而且我有一个矩阵:

MatrixXi x = MatrixXi::Random(5);
Run Code Online (Sandbox Code Playgroud)

我想使用随机抽取的排列随机置换行和列(对于行和列只有一个排列),即如果我有一个发送索引[0,1,2,3,4]的排列 - > [3,4,2,1,0]比我想用相同的排列重新排序行和列.

第1部分:我无法在线找到PermutationMatrix的示例,而且我无法弄清楚语法.

第2部分:如何获得随机置换的索引向量传递给它?也许std :: random_shuffle?

更新:

这是获得一组混乱索引的(可能是低效的)方法:

std::vector<int> perm;
for (int i=0; i<5; ++i) {
    perm.push_back(i);
}

std::random_shuffle(perm.begin(), perm.end());
Run Code Online (Sandbox Code Playgroud)

所以现在的问题是我如何重新排序我的矩阵x,以便它的行/列按烫发排序?

更新2:

越来越近,这是有效的(思想来源:cplusplus.com):

int myrandom (int i) { return std::rand()%i;}

PermutationMatrix<Dynamic,Dynamic> perm(5);

perm.setIdentity();
for (int i=dim-1; i>0; --i) {
    swap (perm.indices()[i],perm.indices()[myrandom(i+1)]);
}

cout << "original x" << x << endl << endl;
cout << "permuted x" << perm * x * perm << endl << endl;
Run Code Online (Sandbox Code Playgroud)

任何人都知道如何使用random_shuffle做到这一点?(参见以下不起作用的尝试.)

(额外的话:如果烫发是1e4 x 1e4矩阵,有关perm*x*perm是否有效的任何想法?)

gga*_*ael 9

使用std :: random_shuffle非常好,那么你必须使用PermutationMatrix:

PermutationMatrix<Dynamic,Dynamic> perm(size);
perm.setIdentity();
std::random_shuffle(perm.indices().data(), perm.indices().data()+perm.indices().size());
A_perm = A * perm; // permute columns
A_perm = perm * A; // permute rows
Run Code Online (Sandbox Code Playgroud)

  • 这正是PermutationMatrix :: operator*正在做的事情!如果你写的话,它甚至可以就地工作:`A = perm*A`. (2认同)