2017-07-26 52 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