2017-07-26 53 views
1

我想解决一个线性方程Ax = b使用特征的A作为平方2D矢量的能力。我有A和B分别作为基于C++的2D矢量和1D矢量。但是,我无法找到将它们的值传递给特征格式矩阵和向量的方法。你能让我如何以Eigen格式复制变量吗? 此外,开始时应该包含哪些可以使用Map类作为可能的溶剂? 下面是代码:将矢量的值传递给特征库格式

#include <iostream> 
#include <vector> 

#include "Eigen/Dense" 

using namespace std; 
using namespace Eigen; 
int main() 
{ 
    // Let's consider that the A and b are following CPP based vectors: 
    vector<vector<double>> mainA= { { 10.,11.,12. },{ 13.,14.,15. },{ 16.,17.,18. } }; 
    vector<double> mainB = { 2.,5.,8. }; 

    // ??? Here I need to do something to pass the values to the following Eigen 
    //format matrix and vector 

    MatrixXf A; 
    VectorXf b; 

    cout << "Here is the matrix A:\n" << A << endl; 
    cout << "Here is the vector b:\n" << b << endl; 
    Vector3f x = A.colPivHouseholderQr().solve(b); 
    cout << "The solution is:\n" << x << endl; 

} 
+0

为什么不*只使用特征类型?为什么你需要C++向量? –

+0

@Some程序员伙计原因是目前我有现有的载体,我需要为我的操作使用这些值! – ReA

+0

我在这里找到了一些东西:但不知道如何正确使用它,我应该在开始时包含什么! – ReA

回答

0

正如在评论中提到的,本征::地图<>应该做的伎俩。 通常你会摆脱不使用Unaligned,而是正确性/稳定性,最好使用它:

auto A = Eigen::Map<Eigen::MatrixXd, Eigen::Unaligned>(mainA.data(), mainA.size(), mainA[0].size()) 
auto b = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(mainB.data(), mainB.size()); 

Vector3d x = A.colPivHouseholderQr().solve(b); 

要回答以下关于鲁棒性的问题:这是可以做到使用辅助功能:

template <typename T, int Align> 
Eigen::Map<Eigen::Matrix<T, -1, -1>, Align> CreateMatrix(const std::vector<std::vector<T>>& x) 
{ 
    int R = x.size(); 
    assert(!x.empty()); 
    int C = x[0].size(); 
    #ifndef NDEBUG 
    for(int r=1; r < R; r++) 
     assert(x[r].size() == x[0].size()); 
    #endif 
    return auto A = Eigen::Map<Eigen::Matrix<T,-1,-1>, Align>(x.data(), R, C); 
} 

虽然它看起来很冗长,但它会进行很多完整性检查,然后您可以依赖所有代码进行单元测试。

+0

我想知道是否有更可靠的方法来定义基于特征格式的矩阵或向量?我问,因为我有一个内存(与malloc相关的东西)在我的代码泄漏,你可以找到我的问题[这里](https://stackoverflow.com/questions/45339532/memory-crash-in-just-2nd-轮对的一换环路包括-本征函数)。感谢你的帮助。 – ReA