Coefficient-wise custom functions in Eigen

南笙酒味 提交于 2020-02-01 18:13:20

问题


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

回答1:


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;
}


来源:https://stackoverflow.com/questions/21728341/coefficient-wise-custom-functions-in-eigen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!