整理下Eigen庫的教程,參考:http://eigen.tuxfamily.org/dox/index.html
存儲順序
對於矩陣和二維數組有兩種存儲方式,列優先和行優先。
假設矩陣:
按行優先存儲,內存中形式如下:
8 2 2 9 9 1 4 4 3 5 4 5
列優先,內存格式:
8 9 3 2 1 5 2 4 4 9 4 5
Matrix<int, 3, 4, ColMajor> Acolmajor;
Acolmajor << 8, 2, 2, 9,
9, 1, 4, 4,
3, 5, 4, 5;
cout << "The matrix A:" << endl;
cout << Acolmajor << endl << endl;
cout << "In memory (column-major):" << endl;
for (int i = 0; i < Acolmajor.size(); i++)
cout << *(Acolmajor.data() + i) << " ";
cout << endl << endl;
Matrix<int, 3, 4, RowMajor> Arowmajor = Acolmajor;
cout << "In memory (row-major):" << endl;
for (int i = 0; i < Arowmajor.size(); i++)
cout << *(Arowmajor.data() + i) << " ";
cout << endl;
輸出
The matrix A:
8 2 2 9
9 1 4 4
3 5 4 5
In memory (column-major):
8 9 3 2 1 5 2 4 4 9 4 5
In memory (row-major):
8 2 2 9 9 1 4 4 3 5 4 5
PlainObjectBase::data()函數可以返回矩陣中第一個元素的內存位置。
存儲順序及選擇
Matrix類模板中可以設定存儲的方向,RowMajor表示行優先,ColMajor表示列優先。默認是列優先。
如何選擇存儲方式呢?
- 如果要和其他庫合作開發,為了轉化方便,可以選擇同樣的存儲方式。
- 應用中涉及大量行遍歷操作,應該選擇行優先,尋址更快。反之亦然。
- 默認是列優先,而且大多庫都是按照這個順序的,默認的不失為較好的。
總結
本來想春節前任務比較少,翻譯完所有的Eigen系列的。但是我的目的是為了使用google的非線性優化庫ceres,介紹了這些基本知識也夠用了,如果遇到不清楚的函數可以直接到Eigen的官網查詢。
這個系列很簡單,只是入門。有更深理解了再續寫。