2014-09-23 41 views
8

這是可以由非本徵用戶回答的問題初始化一個恆定的特徵矩陣...在頭文件

我想使用本徵API來初始化在頭文件中的常數矩陣,但艾根似乎沒有提供一個構造函數來實現這一點,下面是我的嘗試:

// tried the following first, but Eigen does not provide such a constructor 
//const Eigen::Matrix3f M<<1,2,3,4,5,6,7,8,9; 
// then I tried the following, but this is not allowed in header file 
//const Eigen::Matrix3f M; 
//M <<1,2,3,4,5,6,7,8,9; // not allowed in header file 

什麼是替代在頭文件實現這一目標?

+0

如果它是在頭文件中,該數據可以被複製爲每個源包含它的文件,浪費內存。 – 2014-09-24 09:41:42

回答

9

至少有兩種可能性。第一種是使用本徵的逗號初始化劑的特點:

Eigen::Matrix3d A((Eigen::Matrix3d() << 1, 2, 3, 4, 5, 6, 7, 8, 9).finished()); 

第二使用Matrix3d(const double*)構造從一個原始指針,其複製數據。在這種情況下,這些值必須按相同的順序比所述目的地的存儲順序來提供,所以列方向在大多數情況下:

const double B_data[] = {1, 4, 7, 2, 5, 8, 3, 6, 9}; 
Eigen::Matrix3d B(B_data); 
+0

不是逗號初始值設定項按行填充矩陣,而原始數據數組初始化是否按列填充?所以你會得到所需矩陣的轉置? – 2017-12-13 08:15:30

+0

確切的,我已經更新了答案。 – ggael 2017-12-13 09:26:34

1

你不能在這樣的功能之外放置任意代碼。

請嘗試以下操作。該實現甚至可以放在源文件中以加快編譯速度。

const Eigen::Matrix3f& GetMyConst() 
{ 
    static const struct Once 
    { 
     Eigen::Matrix3f M; 

     Once() 
     { 
      M <<1,2,3,4,5,6,7,8,9; 
     } 
    } once; 
    return once.M; 
} 
1

我還沒有看到一個辦法徹底做一個頭,但 這應該工作:

const Eigen::Matrix3f& getMyConst() 
{ 
    static Eigen::Matrix3f _myConstMatrix((Eigen::Matrix3f() << 1,2,3,4,5,6,7,8,9).finished())); 

    return _myConstMatrix; 
} 

#define myConst getMyConst() // To access it like a variable without "()" 

我從來沒有與本徵工作,所以我不能測試它...