首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在特征求解器中从向量中检索值

在特征求解器中从向量中检索值
EN

Stack Overflow用户
提问于 2017-08-11 00:07:15
回答 2查看 720关注 0票数 1

我正在使用Eigen Solver。我在从我创建的矢量/矩阵中检索值时遇到问题。例如,在下面的代码中,我没有错误,但得到了一个运行时错误。

代码语言:javascript
复制
#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中的值检索到我选择的变量(我需要这样做,因为这将是我编写的另一个函数中的一个参数)。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-08-11 00:28:32

使用

代码语言:javascript
复制
vector<float> c(3);

代码语言:javascript
复制
for (int i = 0; i < 3; i++)
{
    c.push_back(x[i]);
    cout << c[i] << " ";
}
票数 3
EN

Stack Overflow用户

发布于 2017-08-11 00:31:15

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

代码语言:javascript
复制
#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';
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45618610

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档