10

I have a do_magic method which takes a double and adds 42 to it. I'd like to apply this method to each coefficient of a Eigen::Matrix or Eigen::Array (that means, I wouldn't mind if it's only possible with one of both types).

Is this possible?

Like this:

Eigen::MatrixXd m(2, 2);    
m << 1,2,1,2;    
m.applyCoefficientWise(do_magic);
// m is now 43, 44, 43, 44
wal-o-mat
  • 7,158
  • 7
  • 32
  • 41

1 Answers1

11

You can use unaryExpr, though this returns a new view onto the matrix, rather than allowing you to modify the elements in place.

Copying the example out of the documentation:

double ramp(double x)
{
  if (x > 0)
    return x;
  else 
    return 0;
}
int main(int, char**)
{
  Matrix4d m1 = Matrix4d::Random();
  cout << m1 << endl << "becomes: " << endl << m1.unaryExpr(ptr_fun(ramp)) << endl;
  return 0;
}
James
  • 24,676
  • 13
  • 84
  • 130
  • 5
    I'll add to that, that if you need to do efficient, disjoint and in place modification of the elements, you could always use the ugly std::for_each on m.data(). However the cost of the above may be perfectly acceptable depending on what you do with m afterwards (since it implements lazy evaluation). – Richard Vock Feb 12 '14 at 13:14
  • Both the answer and the comment are exaclty what I was looking for! Thank you. – wal-o-mat Feb 12 '14 at 13:15