c++: Eigen Library newbie sort

c++, eigen, sorting

Solution

Eigen matrices are column-major per default. That means, that a row of a matrix is not a contiguous C array and you cannot use the data pointer as an iterator.

For example, a 3x4 matrix would be stored as:

0 3 6  9
1 4 7 10
2 5 8 11

Now, `row(1)` would be

1 4 7 10

But the pointer iterator you are passing to `nth_element()` will access

1 2 3 4

Your code works if you change your `matrix` typedef to row-major:

typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> matrix;

Update: Your edited example works since you copy the row to a vector. For vectors (one-dimensional matrices), it does not matter if the data is stored row-major or column-major.

Problem

I can't for the life of me work out why this isn't working correctly. It doesn't seem to return the kth element. ``` typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> matrix; double test(matrix& D, int k) { auto d = D.row(1); std::nth_element(d.data(),d.data()+k, d.data()+d.size()); return d(k) ; } ``` I have also tried ``` template <typename ScalarType, typename Derived> void Sort(Eigen::MatrixBase<Derived> &xValues) { std::sort(xValues.derived().data(), xValues.derived().data()+xValues.derived().size()); } double test(matrix& D, int k) { auto d = D.row(1); Sort<double>(d); return d(k) ; } ``` Any help much appreciated. Edit:- I have just tried changing ``` auto d = D.row(1); ``` to ``` Eigen::VectorXd rowD = D.row(1); .... ``` and it seems to work ok. Slightly confused by that.

Original source