Eigen unaryExpr gotcha, need to set via assignment

Alec Jacobson

June 23, 2014

weblog/

I tried to use eigen's unaryExpr with a function using references to alter a matrix:

MatrixXd X;
...
X.unaryExpr([](double & x){ x = 0});

But X was left unchanged. Thinking I might need to use a function with a return I tried:

X.unaryExpr([](double & x)->return{ return 0});

but still X was unchanged. It seems that unaryExpr is a const operation so I must assign the result back into X. This works:

X = X.unaryExpr([](double & x)->return{ return 0});