0

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

MatrixXd m = ...;

std::function<double(double)> f = ...

m1 = m.apply(f);

Is there a way to achieve this result?`

user1559897
  • 1,454
  • 2
  • 14
  • 27

2 Answers2

4

The unaryExpr template member function takes anything with a call operator (function pointer, functor, lambda, std::function) and applies it to every element of the matrix. Keep in mind that the matrix must not alias!

#include <functional>
#include <iostream>
#include <Eigen/Core>

double square(double x)
{
    return x*x;
}

int main()
{
    Eigen::MatrixXd m = Eigen::MatrixXd::Random(2,2);
    std::cout << m << "\n";
    std::function<double(double)> func = square;
    m = m.unaryExpr(func);
    std::cout << m << "\n";
}
Henri Menke
  • 10,705
  • 1
  • 24
  • 42
0

You may always do it in a brut-force way meaning in a double loop:

for (int j1; j1 < m.rows(); j1++){
    for (int j2; j2 < m.cols(); j2++){
        m(j1, j2) = f(m(j1, j2));
    }
}
freude
  • 3,632
  • 3
  • 32
  • 51