Is it possible to initialize a const Eigen matrix?
Asked Answered
S

2

16

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...

Stoll answered 6/8, 2014 at 11:35 Comment(2)
Do you mean that library: eigen.tuxfamily.org?Stagestruck
Yes, exactly! Version 3.2.1Slacken
L
14

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;
};
Logicize answered 6/8, 2014 at 11:46 Comment(3)
Unfortunately, this doesn't work. I get the following error: no matching function for call to 'Eigen::Matrix<double, 5, 1, 2>::Matrix(Eigen::CommaInitializer<Eigen::Matrix<double, 5, 1, 2> >&)'Slacken
@JanRüegg forgot the "finished" part, sorryLogicize
Does this copy the data? I get the impression that Eigen's hasn't fully implemented move yet.Providential
S
7

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;
};
Subglacial answered 6/8, 2014 at 11:44 Comment(1)
In what file should you put the utility function? If you put it in the cpp file where the class is initialized, would it pollute the global namespace?Erdei

© 2022 - 2024 — McMap. All rights reserved.