2013-04-07 48 views
4

行/矩阵的列我使用本征和我有一个矩阵:随机置换与本征

MatrixXi x = MatrixXi::Random(5); 

我想随机置换行和使用随机抽取排列列(对于行和列都只是一个置换),即如果我有一个发送索引[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()); 

所以,现在的问题是,我该怎么办重新安排我的矩阵X,使得它的行/列按perm排序?

更新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; 

任何人都知道如何使用random_shuffle做到这一点? (见的尝试未下面工作。)

(奖金:在烫发* X *烫发是否会有效的任何想法,如果烫发是1E4 X 1E4矩阵?)

回答

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 
+0

感谢ggael。这很接近,但是perm.indices()没有迭代器AFAIK。我收到错误:'Eigen :: PermutationMatrix <-1, -1> :: IndicesType'没有名为'begin'的成员。我用一半的编辑来编辑我的问题,但据我可以告诉工作代码,但我仍然想知道如何使用random_shuffle! – stackoverflax 2013-04-08 00:25:58

+0

哎呀,我太快了,现在已经修正了。 – ggael 2013-04-08 11:26:32

+0

对于在Google上发现此问题的任何人都会有相当的更新:如果您希望将相同的排列应用于行和列,则需要使用:'perm.transpose()* x * perm' – stackoverflax 2013-09-19 02:16:46