I would like to use the Eigen matrix library as the linear algebra engine in my program. Eigen uses expression templates to implement lazy evaluation and to simplify loops and calculations.
For example:
#include<Eigen/Core>
int main()
{
int size = 40;
// VectorXf is a vector of floats, with dynamic size.
Eigen::VectorXf u(size), v(size), w(size), z(size);
u = 2*v + w + 0.2*z;
}
Since Eigen uses expression templates, code like
u = 2*v + w + 0.2*z;
In the above mentioned sample reduces to a single loop of length 10 (not 40, the floats are put into regiser by chunks of 4) without creating a temporary. How cool is that?
But if I integrate the library like this:
class UsingEigen
{
public:
UsingEigen(const Eigen::VectorXf& data):
data_(data)
{}
UsingEigen operator + (const UsingEigen& adee)const
{
return UsingEigen(data_ + adee.data_);
}
...
private:
Eigen::VectorXf data_;
}
Then the expressions like:
UsingEigen a, b, c, d;
a = b + c + d;
cannot take advantage of the way Eigen is implemented. And this is not the last of it. There are many other examples, where expression templates are used in Eigen.
The easy solution would be not to define the operators by myself, make data_
public and just write expressions like:
UsingEigen a, b, c, d;
a.data_ = b.data_ + c.data_ + d.data_;
This breaks encapsulation, but it preserves the efficiency of Eigen.
Other way could be to make my own operators, but let them return expression templates. But since I am a beginner in C++, I do not know if this is the right way to go.
I am sorry if the question is too general in nature. I am a beginner and have noone to ask. Up until now I was using std::vector<float>
everywhere, but now I need to use matrices also. To switch from std::vector<float>
to Eigen in my entire project is a big step and I am afraid of making a wrong call right in the start. Any advice is welcomed!
(a+b)*c
will be something likeExprCwiseAdd*UsingEigen
(the name is made up, don't recall it any longer), and there will have to beExprCwiseAdd*UsingEigen
defined somewhere, but alsoExprCwiseAdd*ExprCWiseAdd
and so on. In short, the addition will not haveUsingEigen
as return type. (You might have a look at boost::proto which is a framework for expression templates). Good luck. – LilliamlillianEigen
classes, and only use your wrappers as the respective input and output. Intermediate steps then use the actualEigen
data. And you don’t need to expose variables, you can use functions that return (for instance) references to the classes. True, this still exposes data. I feel your pain. – Ormuz