Jan Rüegg
Jan Rüegg

Reputation: 10075

Is it possible to initialize a const Eigen matrix?

I have the following class:

class Foo
{
public:
   Foo(double a, double b, double c, double d, double e)
   // This does not work:
   // : m_bar(a, b, c, d, e)
   {
      m_bar << a, b, c, d, e;
   }

private:
   // How can I make this const?
   Eigen::Matrix<double, 5, 1, Eigen::DontAlign> m_bar;
};

How Can I make m_bar const and initialize it width a to f as values in the constructor? C++11 would also be fine, but initializer lists don't seem to be supported by eigen...

Upvotes: 16

Views: 8217

Answers (2)

Jarod42
Jarod42

Reputation: 218323

You may do a utility function

Eigen::Matrix<double, 5, 1, Eigen::DontAlign>
make_matrix(double a, double b, double c, double d, double e)
{
    Eigen::Matrix<double, 5, 1, Eigen::DontAlign> m;

    m << a, b, c, d, e;
    return m;
}

And then:

class Foo
{
public:
   Foo(double a, double b, double c, double d, double e) :
       m_bar(make_matrix(a, b, c, d, e))
   {
   }

private:
   const Eigen::Matrix<double, 5, 1, Eigen::DontAlign> m_bar;
};

Or you can inline that function and using finished() :

class Foo
{
    using MyMatrice = Eigen::Matrix<double, 5, 1, Eigen::DontAlign>;
public:
   Foo(double a, double b, double c, double d, double e) :
       m_bar((MyMatrice() << a, b, c, d, e).finished())
   {
   }

private:
   const MyMatrice m_bar;
};

Upvotes: 7

Marco A.
Marco A.

Reputation: 43662

Simplest solution I see since the class also defines a copy constructor:

class Foo
{
public:
   Foo(double a, double b, double c, double d, double e) :
       m_bar( (Eigen::Matrix<double, 5, 1, Eigen::DontAlign>() << a, b, c, d, e).finished() )
   {
   }

private:
   const Eigen::Matrix<double, 5, 1, Eigen::DontAlign> m_bar;
};

Upvotes: 14

Related Questions