PThomasCS PThomasCS - 1 year ago 135
C++ Question

Extending Eigen Library to Include Sorting

I would like to extend the C++ Eigen library to include a command v.sort(); I'm using the EIGEN_MATRIXBASE_PLUGIN based approach outlined here.

The code below (in my "MatrixBaseAddons.h") does not work, because the "result" object does not get loaded with a copy of "this"---in the debugger, "result.rows()" is an uninitialized value not equal to derived()->rows(). How do I actually make a copy of "this" and put it in "result"?

MatrixBase<Derived> sort(bool ascending = true) const {
MatrixBase<Derived> result = derived();
return result;

void sortInPlace(bool ascending = true) {
std::sort(derived().data(), derived().data() + derived().size());
if (!ascending)

Answer Source

MatrixBase is an abstract class. You need to return a Matrix<> object with appropriate scalar type and sizes. You can directly use the typedef PlainObject for that:

PlainObject sort(bool ascending = true) const {
  PlainObject res = derived();
  return res;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download