This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Randomize rows in MatrixX

Tags: None
(comma "," separated)
linello
Registered Member
Posts
56
Karma
0
OS

Randomize rows in MatrixX

Thu Apr 14, 2011 8:22 am
Hi you all,

I'm wondering if is possible in Eigen to randomize the order of rows (or columns) in a MatrixX.

Thanks again for your great software!
linello
Registered Member
Posts
56
Karma
0
OS

Re: Randomize rows in MatrixX

Fri Apr 15, 2011 6:49 am
This could be a stupid solution, but to use it I need to create a temporary object.

Code: Select all
// This is our random matrix
MatrixXd A = MatrixXd::Random(4,4);

// Then push each row of A in a std::vector of rows
vector< Matrix<double, 1, Dynamic > > vRows( A.rows() );
for (unsigned int i=0; i< A.rows(); i++ )
   vRows[i] = A.row(i);

// then using STL algorithm we shuffle the vector
random_shuffle( vRows.begin(), vRows.end() );


// ..and copy each row again into A
for (unsigned int i=0; i< A.rows(); i++ )
   A.row(i); = vRows[i];



I understand that this is not the optimal solution because we need to create two objects, but I'm wondering if std::random_shuffle() can help in this case acting directly on rows of MatrixXd.

Last edited by linello on Fri Apr 15, 2011 1:59 pm, edited 1 time in total.
jitseniesen
Registered Member
Posts
204
Karma
2

Re: Randomize rows in MatrixX

Fri Apr 15, 2011 1:57 pm
One possibility is to construct a vector containing 0, 1, 2, 3, ..., permute this vector with random_shuffle, and then apply the permutation represented by the vector to the matrix:

Code: Select all
MatrixXd A = /* whatever */;
VectorXi indices = VectorXi::LinSpaced(A.rows(), 0, A.rows());
std::random_shuffle(indices.data(), indices.data() + A.rows());
A = indices.asPermutation() * A;

It uses a vector indices, but I think that's acceptable. More problematic may be that a temporary matrix is created in the last line.

linello wrote:I'm wondering if std::random_shuffle() can help in this case acting directly on rows of MatrixXd.

I came up with the following code, which does not work:

Code: Select all
MatrixXd A = MatrixXd::Random(4, 4);
std::vector<MatrixXd::RowXpr> vRows; // note the type!
for (int i=0; i < A.rows(); i++)
  vRows.push_back(A.row(i));
std::random_shuffle(vRows.begin(), vRows.end());

The idea here is to fill the std::vector with the expression objects returned by A.row(i) instead of converting it to a Eigen::VectorXd. However, this does not work when I try it. I don't know why.
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Randomize rows in MatrixX

Mon Apr 18, 2011 8:10 am
Code: Select all
A = indices.asPermutation() * A;


the above statement is evaluated "in-place", without any temporary. So this is definitely the right way to go.


Bookmarks



Who is online

Registered users: bartoloni, Bing [Bot], Evergrowing, Google [Bot], q.ignora