16

I am trying to traverse Eigen::MatrixXd matrix. However, there does not seem to be a function that returns the columns size nor the row size. Does anybody have an idea on how to do this?

Tom Oconnor
  • 393
  • 2
  • 5
  • 14

2 Answers2

23

This should work...

#include <Eigen/Dense>

int main()
{
    Eigen::MatrixXd matrix(3, 4);

    // An explicit cast required on rows() and
    // cols() to convert the output type of
    // Eigen::Index into int
    int r = static_cast<int>(matrix.rows());
    int c = static_cast<int>(matrix.cols());

    for (int i = 0; i < r; ++i)
    {
        for (int j = 0; j < c; ++j)
        {
            std::cout << matrix(i,j) << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}
rayryeng
  • 102,964
  • 22
  • 184
  • 193
Icarus3
  • 2,310
  • 14
  • 22
  • the code above leads to a warning like "losing data by converting Eigen::Index type to int". do you have more elegant solutions? thanks – MIAWANG Oct 16 '21 at 12:45
  • You can provide an explicit cast to convert the output of `rows()` and `cols()` to `int`. This way you can avoid using `Eigen::Index` in the `for` loops, so `int r = static_cast(matrix.rows()); int c = static_cast(matrix.cols());` – rayryeng Aug 10 '23 at 22:32
2

Same answer as @Icarus3 but without the warnings:

#include <Eigen/Dense>

int main()
{
  Eigen::MatrixXd matrix(3, 4);

  auto const rows = matrix.rows();
  auto const cols = matrix.cols();

  for (Eigen::Index i{0}; i < rows; ++i) {
    for (Eigen::Index j{0}; j < cols; ++j) {
      std::cout << matrix(i, j) << " ";
    }
    std::cout << "\n";
  }
  std::cout << std::endl;

  return 0;
}