Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply function to all Eigen matrix element

Tags:

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?

like image 870
Nick Avatar asked Nov 18 '15 17:11

Nick


2 Answers

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; } 
like image 196
vsoftco Avatar answered Sep 27 '22 22:09

vsoftco


vsoftco's answer is very general and is good for custom functions. However, there is a simpler way for many of the commonly used functions. Adapting his example we can use arrays and it looks like this:

#include <iostream> #include <Eigen/Core>  int main() {     Eigen::MatrixXd m(2, 2);     m << 0, 1, 2, 3;     std::cout << m << "\nbecomes:\n";     std::cout << m.array().exp() << std::endl;     return 0; } 
like image 20
Avi Ginsburg Avatar answered Sep 27 '22 22:09

Avi Ginsburg