## Introduction to Eigen Library
Eigen 是一個高效能的 C++ 線性代數庫,專門用來處理矩陣運算和數學計算。它是 header-only(不需要額外編譯),只要把library加到專案裡面就可以直接使用。筆者會用到這個函式庫是因為要做機器人的逆向運動學計算等等。
我覺得最大的好處是他的語法和Matlab高度相似,index是用()來表示:laughing:
## 矩陣及向量宣告
- 宣告一個已知大小的矩陣
```cpp
Matrix<double, 3, 3> A; // 引數可以決定(row, column)
```
- 矩陣賦值
有兩種方法,使用`<<`或是像matlab一樣直接用index取用。==需要注意的是matlab的index從1開始;但是Eigen沿用C語言模式從0開始。==
```cpp!
Matrix<double, 3, 3> A; // declaration matrix A
// two ways to assign value to matrix A
A << 1,2,3,
4,5,6,
7,8,9; // use << to assign value
A(0,0) = 1; // use index to access/assign value
A(1,2) = 2;
```
如果要新增一個特殊的矩陣,像是單位矩陣、零矩陣或是元素全部都是1的矩陣,Eigen也有提供一些方便的函式
```cpp=
// Eigen // Matlab
MatrixXd::Identity(rows,cols) // eye(rows,cols)
C.setIdentity(rows,cols) // C = eye(rows,cols)
MatrixXd::Zero(rows,cols) // zeros(rows,cols)
C.setZero(rows,cols) // C = ones(rows,cols)
MatrixXd::Ones(rows,cols) // ones(rows,cols)
C.setOnes(rows,cols) // C = ones(rows,cols)
MatrixXd::Random(rows,cols) // rand(rows,cols)*2-1
C.setRandom(rows,cols) // C = rand(rows,cols)*2-1
VectorXd::LinSpaced(size,low,high) // linspace(low,high,size)'
v.setLinSpaced(size,low,high) // v = linspace(low,high,size)'
```
## 矩陣及向量運算
當然也有矩陣、向量乘法相關的運算。比較方便的地方是做乘法運算的時候可以直接使用+-/等運算子,這方面和matlab比較來很像,也很方便。
```cpp=
Vector3f x;
Vector3f y;
Matrix<double, 3, 3> M;
x.dot(y); // inner product
x.cross(y);
y = M*x;
```
最重要的是還有提供pseudo inverse,不用自己做svd分解幹嘛的
```cpp=
// jacobian is a matrix
jacobian.completeOrthogonalDecomposition().pseudoInverse();
```
## 其他性質
其他常用的則是獲取矩陣的長寬、或是向量的norm之類的。
```cpp=
Vector3f x;
Matrix<double, 3, 3> mat;
// vector related
x.norm();
x.squaredNorm();
x.size();
// matrix related
mat.rows();
mat.col();
```
## 參考資料
以上只是列出比較常用的操作,詳細教學可以見下面兩個網站
- [Eigen: Main page](https://eigen.tuxfamily.org/dox/)
- [C++矩陣庫Eigen快速入門](https://jasonblog.github.io/note/third-party/cju_zhen_ku_eigen_kuai_su_ru_men.html)