ver*_*man 2 c++ math matrix eigen
由于 Eigen C++ 库不包含计算矩阵的内置方法,因此sign(x)我正在寻找执行此操作的最佳方法。有关 的定义,sign()请参阅Matlab 文档,尽管我实际上并不需要 0 元素的情况。我想出的方法如下。
Eigen::MatrixXf a = Eigen::MatrixXf(2,2);
a << -0.5, 1.0,
0.3, -1.4;
// Temporary objects containing 1's and -1's
const Eigen::MatrixXi pos = Eigen::MatrixXi::Ones(a.rows(), a.cols());
const Eigen::MatrixXi neg = Eigen::MatrixXi::Ones(a.rows(), a.cols()) * -1;
// Actually filling of the matrix sign(a)
Eigen::MatrixXi a_sign = (a.array() >= 0).select(pos, neg);
std::cout << a << std::endl << std::endl;
std::cout << a_sign << std::end;
Run Code Online (Sandbox Code Playgroud)
这是有效的,因此输出由下式给出
-0.5 1
0.3 -1.4
-1 1
1 -1
Run Code Online (Sandbox Code Playgroud)
不过我想知道是否有更好的方法来做到这一点?创建两个临时矩阵似乎很麻烦,并且在处理非常大的矩阵时可能会变得相当慢。