我有一种情况,我从具有双元素的一个中派生出一个具有复杂元素的 Eigen3 矩阵。目前我只是遍历行和列并一一填写条目。我想知道是否有人知道以下方面的任何方法:
complexMatrix = doubleMatrix.unaryExpr(transform)
Eigen 中有一个称为cast的运算符。由于模板的原因,声明看起来很吓人,但使用起来非常简单。
我认为这应该有效
complexMatrix = doubleMatrix.cast< std::complex<double> >();
编辑,嗯好的......有一种方法可以做到这一点。文档中有一个示例:http: //eigen.tuxfamily.org/dox/classEigen_1_1MatrixBase.html#a23fc4bf97168dee2516f85edcfd4cfe7
但是我相信,要获得正确的类型,您需要组合cast
和仿函数。
complexMatrix = doubleMatrix.cast< std::complex<double> >().unaryExpr( FUNCTOR );
当然,仿函数预计将被设计为与复杂Scalar
类型一起使用。您还可以将fnc_ptr
包装器与普通函数一起使用,如示例中所示。
注意:当使用接受双精度并返回复数的仿函数类时,可能可以跳过cast
,但我没有设法做到这一点。这会很棘手。我也不认为这是必要的,因为cast
可能不会引入任何真正的开销。
编辑:工作示例。
它确实会从来回转换 2 次x
中引入一点开销,但我希望它与实际的仿函数体相比可以忽略不计。double
complex
#include <Eigen/Core>
#include <iostream>
using namespace Eigen;
using namespace std;
std::complex<double> functor(double x){
//complicated stuff
return std::complex<double> (x, -2*x) ;
}
std::complex<double> wrapper(std::complex<double> x)
{
//nothing is lost here, as we expect x to have only real part
//from being upcasted from the original matrix
double xReal = x.real();
return functor(xReal);
}
int main(int, char**)
{
Matrix4d m1 = Matrix4d::Random();
cout << m1 << endl << "becomes: " << endl
<< m1.cast< std::complex<double> >().unaryExpr(ptr_fun(wrapper)) << endl;
return 0;
}
unaryExpr 可以从函子推导出返回类型,所以可以这样做:
#include <Eigen/Core>
std::complex<double> functor(double x){
return std::complex<double> (-x, x) ;
}
int main(int, char**)
{
Eigen::Matrix3d m1 = Eigen::Matrix3d::Random();
Eigen::Matrix3cd m2 = m1.unaryExpr(std::ptr_fun(functor));
}
并带有一个仿函数类:
#include <Eigen/Core>
struct Functor {
typedef std::complex<double> result_type;
std::complex<double> operator()(double x) const {
return std::complex<double> (-x, x) ;
}
};
int main(int, char**)
{
Eigen::Matrix3d m1 = Eigen::Matrix3d::Random();
Eigen::Matrix3cd m2 = m1.unaryExpr(Functor());
}