Search code examples
c++eigeneigen3

Save Eigen array row in a variable


I'm trying to extract the j-th row from an Eigen::ArrayXXi and store it in a variable. This is what I tried.

Eigen::Array<int, arr.rows(), arr.cols()> row = arr.row(j);

But I get the following error highlighting arr.rows()

Non-type template argument of type 'Eigen::Index' (aka 'long') is not an integral constant expression

I am unable to find what the return type of arr.row() is supposed to be. According to the documentation, it's RowExpr, which means nothing to me.


Solution

  • You cannot use

    Eigen::Array<int, arr.rows(), arr.cols()> row = arr.row(j);
    

    Because rows() and cols() aren't constexpr, hence they are not a const expression as written in the error message: https://eigen.tuxfamily.org/dox/structEigen_1_1EigenBase.html#ab75c2d8a783d055db397319c5a330eee .

    You have two choices, if the sizes are known at compile time, hard-code the values, otherwise, as explained in this tutorial https://eigen.tuxfamily.org/dox/group__TutorialArrayClass.html use:

    Eigen::Array<int, Dynamic, Dynamic> row = arr.row(j);
    

    to have dynamic sizes. Fore more information on using Dynamic sizes refer to the documentation of Matrix which is referenced to from the docs of Array: https://eigen.tuxfamily.org/dox/classEigen_1_1Matrix.html

    I can see that Eigen::Array<int, Dynamic, Dynamic> has as alias ArrayXXi: https://eigen.tuxfamily.org/dox/group__arraytypedefs.html#gab2c3a894f02fb9fdbc3de996c9d02312

    Edit as pointed out by user ggael one can also use ArrayXi given that we know at least one dimension, which is 1.