如何在 Eigen3 中找到大小为 N 乘 1 的复 vector 中的最小正实数?例如,在本例中,我想查找值 3.64038
。
#include <Eigen/Dense>
#include <iostream>
using namespace std;
using namespace Eigen;
int main()
{
MatrixXd m(4, 4);
m << 1, 0, 1, 1,
0, 2, 0, 1,
0, 2, 1, 0,
2, 1, 2, 1;
cout << m << endl;
cout << m.eigenvalues() << endl;
return 0;
}
输出
1 0 1 1
0 2 0 1
0 2 1 0
2 1 2 1
(3.64038,0)
(-0.444745,0)
(0.902183,1.01932)
(0.902183,-1.01932)
应排除虚部不等于 0 的 vector 元素。
我编写了以下函数,但想知道是否有一种使用 Eigen 方法的方法。
double findPositiveRealMin(VectorXcd v)
{
VectorXd v_imag = v.imag();
VectorXd v_real = v.real();
for (int i = 0; i < v.rows(); i++)
{
if (v_imag[i] != 0 | v_real[i] <= 0)
v_real[i] = 1.0e16;
}
return v_real.minCoeff();
}
最佳答案
一种选择是创建一个逻辑数组,然后对其调用Eigen::select
。灵感来自https://forum.kde.org/viewtopic.php?f=74&t=91378
在这种情况下:
Eigen::VectorXcd v = m.eigenvalues();
// minimum positive real value with zero imaginary part
Eigen::Array<bool,Eigen::Dynamic,1> cond1 = (v.imag().array() == 0);
Eigen::Array<bool,Eigen::Dynamic,1> cond2 = (v.real().array() > 0);
double some_big_value = 1e16;
std::cout << (cond1 && cond2).select(v.real(), some_big_value).minCoeff() << std::endl;
...或者,作为一句台词:
std::cout << (v.imag().array() == 0 && v.real().array() > 0).select(v.real(), 1e16).minCoeff() << std::endl;
关于c++ - 找到复 vector 中的最低实值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67969172/