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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With