Search code examples
c++eigen

How to get shape (dimensions) of an Eigen matrix?


I'm coming over from Python & Numpy to C++ & Eigen.

In Python I can get the shape (dimensions) of a Numpy array/matrix using the .shape attribute, like so:

import numpy as np

m = np.array([ [ 1, 2, 3], [10, 20, 30] ])
print(m)
# [[ 1  2  3]
#  [10 20 30]]

print(m.shape)
# (2, 3)

Now, when I use Eigen, there doesn't appear to be any attribute or method to retrieve the shape. What's the easiest way to do so?

#include <iostream>
#include "Eigen/Dense"

using std::cout;
using std::endl;
using std::string;
using Eigen::MatrixXd;


int main(int argc, char**argv)
{
    MatrixXd m(2, 3);
    m << 1, 2, 3, 10, 20, 30;

    cout << m << endl;
    //  1  2  3
    // 10 20 30

    cout << "shape: " << WHAT DO I PUT HERE? << endl;

    return 0;
}

Solution

  • You can retrieve the number of rows and columns from an Eigen matrix using the .rows() and .cols() methods, respectively.

    Below is a function get_shape() that returns a string representation of the matrix shape; it contains information analogous to Numpy's .shape attribute.

    The EigenBase type allows the function to accept either a MatrixXd or a VectorXd.

    #include <iostream>
    #include <sstream> // <-- Added
    #include "Eigen/Dense"
    
    using std::cout;
    using std::endl;
    using std::string;
    using std::ostringstream; // <-- Added
    using Eigen::MatrixXd;
    using Eigen::EigenBase;   // <-- Added
    
    template <typename Derived>
    std::string get_shape(const EigenBase<Derived>& x)
    {
        std::ostringstream oss;
        oss  << "(" << x.rows() << ", " << x.cols() << ")";
        return oss.str();
    }
    
    int main(int argc, char**argv)
    {
        MatrixXd m(2, 3);
        m << 1, 2, 3, 10, 20, 30;
    
        cout << "shape: " << get_shape(m) << endl;
        // shape: (2, 3)
    
        return 0;
    }