0

May I please seek help with a computation issue of the matrix library "Eigen."

say i have a functor:

    struct my_F
    {
      double a_,b_;
      my_F(double a,double b):a_(a),b_(b){};
      double operator()(double x){return (x+a)*(x+b);}
    }

Now I want to use this functor to operate on a Eigen::MatrixXd

Eigen::MatrixXd a(10,12);
a.setConstant(2.); 

How do I write something (in a compact and nice way) so that each element of "a" is taken and the functor operation to it is applied.

I can always do it in a loop but is that the only way out ?

Thanks in advance.

user1612986
  • 1,373
  • 3
  • 22
  • 38

1 Answers1

3

You can apply a unaryExpr onto your matrix:

Eigen::MatrixXd M(10,12);
//fill matrix M

auto f = my_F{1.0,2.0};
auto M_new = M.unaryExpr(f);

Note that the result of the transformation M_new is not stored, but evaluated on the fly (as usual in expression template libraries). If you want to store the result, replace "auto M_new" by "Eigen::MatrixXd M_new".

davidhigh
  • 14,652
  • 2
  • 44
  • 75