从特征求解器中的Vector中检索值

时间:2017-08-10 16:07:15

标签: c++ eigen

我正在使用Eigen Solver。我无法从我创建的Vectors / Matrix中检索值。例如,在以下代码中,我没有错误但是出现运行时错误。

#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中的值检索到我选择的变量(我需要这个,因为这将是我写的另一个函数中的参数)。

2 个答案:

答案 0 :(得分:3)

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

#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';
}

答案 1 :(得分:2)

使用

vector<float> c(3);

或者

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