Reputation: 413
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?
Upvotes: 17
Views: 21054
Reputation: 2350
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;
}
Upvotes: 25
Reputation: 31
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;
}
Upvotes: 3