Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coefficient-wise custom functions in Eigen

Tags:

c++

eigen

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
like image 630
wal-o-mat Avatar asked Feb 12 '14 12:02

wal-o-mat


1 Answers

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;
}
like image 126
James Avatar answered Oct 04 '22 23:10

James