1、一句話簡述Eigen
Eigen是一個C++開源線性代數庫,slam中使用Eigen庫進行矩陣、向量乃至旋轉矩陣與變換矩陣的表示和計算
2、Eigen在ubuntu中的安裝
Eigen庫在ubuntu軟件源中提供,所以可以直接在終端輸入以下命令進行安裝:
sudo apt-get install libeigen3-dev |
3、Eigen在ubuntu中的簡單應用
一般而言,庫是由頭文件和庫文件組成,在編譯時不僅在可執行程序中聲明庫的頭文件,而且要將可執行文件與庫文件鏈接,而Eigen是一個由只用頭文件搭建起來的庫,在使用時只需引入Eigen的頭文件即可,不需要鏈接庫文件。Eigen庫的頭文件默認在“/usr/include/eigen3”中,如果不確定可以輸入以下命令查找:
sudo updatedb locate eigen3 |
下面引入一段簡單代碼來表達Eigen的使用:
#include <iostream>
using namespace std;
#include <ctime>
#include <Eigen/Core>
#include <Eigen/Dense>
int main( int argc, char** argv )
{
//聲明矩陣:一個名為m_23的單精度2行3列矩陣,Eigen::Matrix為聲明矩陣的一個模板類,前三個參數為:數據類型,行,列。
Eigen::Matrix<float, 2, 3> m_23;
//基於Eigen::Matrix,有一些內置的類型比如Eigen::Vector3f,指的是:Eigen::Matrix<float,3,1>,表示一個三維向量。其中f表示單精度,d表示雙精度。
Eigen::Vector3d v_3d; //聲明一個三維向量v_3d
//類似地,Matrix3d 實質上是 Eigen::Matrix<double, 3, 3>
Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Zero(); //聲明一個三維矩陣並初始化為零
//輸入數據
m_23 << 1,2,3,4,5,6;
//輸出
cout<<m_23<<endl;
// 用for語句訪問矩陣中的元素
for (int i=0; i<2; i++)
{
for (int j=0; j<3; j++)
cout<<m_23(i,j)<<"\t";
cout<<endl;
}
//矩陣和向量相乘
v_3d << 1, 2, 3;
//要保證輸出數據類型跟輸入數據類型一致,m_23前面聲明為單精度,故用cast()顯式轉換為雙精度。
Eigen::Matrix<double, 2, 1> result = m_23.cast<double>() * v_3d;
cout << result << endl;
//矩陣運算比較簡單
matrix_33 << 1,2,3,4,5,6,7,9,9; // 聲明一個矩陣(可以多試幾種矩陣,看下面的計算輸出什么結果)
cout << matrix_33 << endl;
cout << matrix_33.transpose() << endl; // 轉置
cout << matrix_33.sum() << endl; // 各元素和
cout << matrix_33.trace() << endl; // 跡
cout << 10*matrix_33 << endl; // 數乘
cout << matrix_33.inverse() << endl; // 逆
cout << matrix_33.determinant() << endl; // 行列式
//如何解方程:matrix_33*X = v_3d,有兩種方法:直接求逆法,矩陣分解法。下面分別求解並計時驗證效率,可知直接法比較耗時,運算量大
clock_t time_stt = clock(); // 計時(直接求逆法)
Eigen::Matrix<double,3,1> X= matrix_33.inverse()*v_3d;
cout<<"方程解為:\n"<<X<<endl;
cout <<"計算所需時間:" << 1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC << "ms"<< endl;
// 矩陣分解法
time_stt = clock(); //計時
X = matrix_33.colPivHouseholderQr().solve(v_3d);
cout<<"方程解為:\n"<<X<<endl;
cout <<"計算所需時間:" << 1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC << "ms"<< endl;
return 0;
}
將程序文件保存命名為eigenMatrix.cpp,在ubuntu中我們使用cmake編譯,CMakeLists.txt文件編輯如下:
cmake_minimum_required( VERSION 2.8 ) #創建名為useEigen的工程 project( useEigen ) # 添加Eigen頭文件 include_directories( "/usr/include/eigen3" ) #添加要運行的程序 add_executable( eigenMatrix eigenMatrix.cpp ) |
之后在終端通過cmake編譯得到可執行文件,運行可執行文件得到運行結果如下:
1 2 3
4 5 6
1 2 3
4 5 6
14
32
1 2 3
4 5 6
7 9 9
1 4 7
2 5 9
3 6 9
46
15
10 20 30
40 50 60
70 90 90
-1.5 1.5 -0.5
1 -2 1
0.166667 0.833333 -0.5
6
方程解為:
0
0
0.333333
計算所需時間:0.043ms
方程解為:
1.14652e-15
-9.12374e-16
0.333333
計算所需時間:0.042ms
參考:《視覺slam十四講,從理論到實踐》,高翔,張濤編著。