Eigen库的学习记录(一)
目录
仅供自己理解,如果有错误,还请温柔指教~
Eigen库的下载地址
https://eigen.tuxfamily.org/index.php?title=Main_Page
新建visual studio项目时调用该库的操作流程见
https://blog.csdn.net/MaybeTnT/article/details/109841378
Eigen库的官方文档
https://eigen.tuxfamily.org/dox/
很多不了解的函数可以在里面搜索,以下内容也大多来源于此。
rowwise()
按行操作矩阵,必须和其他操作连用
eg:
m.rowwise().sum() 按行求和
replicate(a,b)
将调用该函数的变量视为元素,复制生成a行b列
eg:
m.replicate(1, 2)
squaredNorm()
矩阵/向量所有元素的平方和
eg1:
m1.squaredNorm()
eg2:
Vector3d v;
v << 1, 2, 3;
cout << "Here is the Vector3d v:" << endl << v << endl;
cout << "Here is the Vector3d v squaredNorm:" << endl << v.squaredNorm() << endl;
Identity()
对角线元素为1的矩阵,可以非方阵
eg1:
cout << Matrix<double, 3, 4>::Identity() << endl;
eg2:
using MatrixX = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>;
MatrixX m2;
using Matrix4 = Eigen::Matrix<double, 4, 4>;
m2 = Matrix4::Identity().replicate(2, 3);
cout << “Here is the matrix m2:” << endl << m2 << endl;
homogeneous()
将向量长度加1,值1作为最后一个元素给到新向量,常用于仿射坐标转换为齐次坐标
齐次坐标是为了平移的加操作变成乘操作,使得元素从三维向量变成四维向量,最后一维元素值为1。
具体请看 //https://zhuanlan.zhihu.com/p/412896170
eg:
Vector3d v = Vector3d::Random();
cout << "v = [" << v.transpose() << "]^T" << endl;
cout << "v.homogeneous() = [" << v.homogeneous().transpose() << "]^T" << endl;
![在这里插入图片描述](https://img-blog.csdnimg.cn/8dbd752cf69a4838a7694b889809b977.png)
determinant()
返回矩阵的行列式值
sparseView()
需要#include <Eigen/Sparse>
将矩阵稀疏表示,节省存储空间。
sparseView(reference, epsilon)两个参数,第一个是非0的参考值,第二个是容差因子,在目前的应用中暂时没有发现有什么实质作用。
eg:
Matrix3d D;
D << 1, 2, 3, 4, 0, 5, 0, 0.5, 9;
cout << "Here is the matrix D:" << endl << D << endl;
SparseMatrix<double> S;
S = D.sparseView(1, 1e-20);//将矩阵D稀疏表示为S
cout << "Here is the matrix S:" << endl << S << endl;
输出如下:
稀疏矩阵S
首先存储的是非0项的值,然后是按列计算的索引。为Nonzero entries
然后存储的是Outer pointers存储的是Nonzero entries中需要在稠密矩阵第一行的索引,例如Nonzero entries中的第4个是(3,0),所以第一行第3列是3。
据此可以组成稠密矩阵如最下方所示,共9个元素。
自己理解:稀疏矩阵并不改变原矩阵各个元素的值以及原矩阵的size,只是存储方式不同
SparseMatrix::InnerIterator
#include <Eigen/Sparse>
//SparseMatrix::InnerIterator
Matrix3d D;
D << 1, 2, 3, 4, 0, 5, 0, 0.5, 9;
cout << "Here is the matrix D:" << endl << D << endl;
SparseMatrix<double> S;
S = D.sparseView(1, 1e-20);
cout << "Here is the matrix S:" << endl << S << endl;
for (int k = 0; k < D.outerSize(); ++k)
for (SparseMatrix<double>::InnerIterator it(S, k); it; ++it)
{
it.value();
it.row(); // row index
it.col(); // col index (here it is equal to k)
it.index(); // inner index, here it is equal to it.row()
cout << k <<" " << it.value() << " " << it.row() << " " << it.col() << " " << it.index() << " " << endl;
}
VectorXd::Zero(n)
生成一个n维的列向量
VectorXd D = VectorXd::Zero(5);
cout << "Here is the matrix D:" << endl << D << endl;
pow()
pow(2,4) = 2^4 = 16
constant()
//初始化一个行数,列数为某常量值的矩阵Constant(Index rows, Index cols, const Scalar& value)
Eigen::MatrixXi pos = Eigen::MatrixXi::Constant(5, 5, -1);
cout << "Here is the matrix pos:" << endl << pos << endl;