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?`
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?`
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";
}
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));
}
}