从特征求解器中的矢量中检索值

retrieving values from Vector in Eigen Solver

本文关键字:检索 特征      更新时间:2023-10-16

我正在使用特征求解器。我无法从我创建的矢量/矩阵中检索值。例如,在下面的代码中,我没有错误,但收到运行时错误。

#include <iostream>
#include <math.h>
#include <vector>
#include <EigenDense>
using namespace std;
using namespace Eigen;
int main()
{
Matrix3f A;
Vector3f b;
vector<float> c;
A << 1, 2, 3, 4, 5, 6, 7, 8, 10;
b << 3, 3, 4;
cout << "Here is the matrix A:n" << A << endl;
cout << "Here is the vector b:n" << b << endl;
Vector3f x = A.colPivHouseholderQr().solve(b);
for (int i = 0; i < 3; i++)
{
c[i] = x[i];
cout << c[i] << " ";
}
//cout << "The solution is:n" << x << endl;
return 0;
} 

如何将 x 中的值检索到我选择的变量(我需要这个,因为这将是我编写的另一个函数中的一个参数(。

使用

vector<float> c(3);

for (int i = 0; i < 3; i++)
{
c.push_back(x[i]);
cout << c[i] << " ";
}

如评论中所述,问题在于c在为其分配值之前没有调整其大小。此外,您实际上不需要Eigen::Vector3f x,但您可以将.solve()操作的结果直接分配给指向vector数据的Map

#include <iostream>
#include <vector>
#include <Eigen/QR>
using namespace Eigen;
using namespace std;
int main()
{
Matrix3f A;
Vector3f b;
vector<float> c(A.cols());
A << 1, 2, 3, 4, 5, 6, 7, 8, 10;
b << 3, 3, 4;
cout << "Here is the matrix A:n" << A << endl;
cout << "Here is the vector b:n" << b << endl;
Vector3f::Map(c.data()) = A.colPivHouseholderQr().solve(b);
for(int i=0; i<3; ++i) std::cout << "c[" << i << "]=" << c[i] << 'n';
}