从Eigen Solver中的Vector中检索值
问题描述:
我正在使用Eigen Solver。我无法从我创建的Vectors/Matrix中检索值。例如,在下面的代码中,我没有错误,但得到运行时错误。从Eigen Solver中的Vector中检索值
#include <iostream>
#include <math.h>
#include <vector>
#include <Eigen\Dense>
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()
操作的结果分配给Map
它指向vector
的数据:
#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';
}
'却得到了一个运行时间error'它是一个秘密?你可以分享吗? – Gluttton
问题是你的'std :: vector c'从来没有被调整过大小3(Eigen没有问题,并且应该从运行时错误的源头看到这个问题) –
chtz
使用'c.resize(b。尺寸());' – RHertel