我有一个 Eigen::MatrixXd
,我想通过按组件应用函数来修改它的所有元素。例如:
MatrixXd m = ...;
for each m[i][j]:
m[i][j] = exp(m[i][j]);
有没有办法达到这个效果?
最佳答案
是的,使用 Eigen::MatrixBase<>::unaryExpr()
成员函数。示例:
#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;
}
关于c++ - 将函数应用于所有特征矩阵元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33786662/