Apply function to all Eigen matrix element

Nick picture Nick · Nov 18, 2015 · Viewed 10.4k times · Source

I have an Eigen::MatrixXd and I would like to modify all its elements by applying a function component-wise. For example:

MatrixXd m = ...;

for each m[i][j]:
  m[i][j] = exp(m[i][j]);

Is there a way to achieve this result?

Answer

vsoftco picture vsoftco · Nov 18, 2015

Yes, use the Eigen::MatrixBase<>::unaryExpr() member function. Example:

#include <cmath>
#include <iostream>

#include <Eigen/Core>

double Exp(double x) // the functor we want to apply
{
    return std::exp(x);
}

int main()
{
    Eigen::MatrixXd m(2, 2);
    m << 0, 1, 2, 3;
    std::cout << m << std::endl << "becomes: ";
    std::cout << std::endl << m.unaryExpr(&Exp) << std::endl;
}