Randomly permute rows/columns of a matrix with eigen

后端 未结 2 1464
感情败类
感情败类 2020-12-29 15:59

I\'m using Eigen and I\'ve got a matrix:

MatrixXi x = MatrixXi::Random(5);

I\'d like to randomly permute the rows and columns using a rando

2条回答
  •  渐次进展
    2020-12-29 16:42

    As stated here: Stackoverflow:

    If you can use C++11 I'd recommend implementing this without using srand() and random_shuffle(); instead you should use the library with std::shuffle.

    First, if possible rand should be avoided. Aside from the fact that it isn't usually a very good pRNG, it also has problems with thread safety due to shared state. The library fixes both these problems by giving the programmer explicit control over pRNG state and by providing several options with guaranteed performance, size, and quality characteristics.

    Secondly, random_shuffle isn't actually specified to use rand so it's theoretically legal for reseeding using srand not to have the effect you want. To get guaranteed results with random_shuffle you have to write your own generator. Moving to shuffle fixes that, as you can directly use standard engines.

    #include        //seed generation
    #include     //shuffle()
    
    int main() {
    
    std::random_device r;
    std::seed_seq rng_seed{r(), r(), r(), r(), r(), r(), r(), r()};
    
    //create random engines with the rng seed
    std::mt19937 eng1(rng_seed);
    
    //create permutation Matrix with the size of the columns
    Eigen::PermutationMatrix permX(inputX.cols());
    permX.setIdentity();
    std::shuffle(permX.indices().data(), permX.indices().data()+permX.indices().size(), eng1);
    inputX = inputX * permX;   //shuffle column wise
    
    }
    

    If you want to shuffle the rows use inputX.rows() instead for the initialization of the Permutation Matrix. And use inputX = permX * inputX instead.

提交回复
热议问题