前言
一、Eigen库的环境配置
Eigen是一个C++的数值计算库,包含矩阵、矢量、数值求解以及相关的算法。在下载页面,选择latest release candidate版本中的zip格式进行下载。
- 先下载好Eigen的安装包
- 配置环境
Eigen的安装包的位置:E:\C++\eigen-3.3.8
在VS中创建一个新项目
对标红部分点右键
点击属性
在包含目录下添加Eigin库的文件地址:E:\C++\eigen-3.3.8
Eigen 是一个基于C++模板的线性代数库,直接将库下载后放在项目目录下,然后包含头文件就能使用了。
二、相关知识介绍
矩阵的定义: Eigen中关于矩阵类的模板函数中,共有六个模板参数,常用的只有前三个。其前三个参数分别表示矩阵元素的类型、行数和列数。
template<typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>
struct traits<Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> >
.......
2.1 Eigen 矩阵定义
#include <iostream>
#include <Eigen/core>
#include <Eigen/Dense>
using namespace Eigen;
using namespace std;
int main()
{
MatrixXd m = MatrixXd::Random(3, 3); //初始化3X3的随机动态矩阵
cout << "Random Matrix:" << endl << m << endl;
m = MatrixXd::Constant(3, 3, 1.2); //3X3的矩阵,每个值都是1.2
cout << "Constant Matrix:" << endl << m << endl;
VectorXd v(3); //创建矩阵v
v << 1, 2, 3; //设置v的值
cout << "Vector:" << v << endl;
RowVectorXd h(3); //设置行矩阵
h << 4, 5, 6;
cout << "RoeVector:" << h << endl;
Matrix<double, 3, 3> A; // 静态矩阵
Matrix<double, 3, Dynamic> B; // 行固定,列不固定
Matrix<double, Dynamic, Dynamic> C; // 行列都不固定,等同与动态矩阵
Matrix<double, 3, 3, RowMajor> E; // 行主要;默认是列为主 Row major; default is column-major.
Matrix3f P, Q, R; // 3x3 float matrix.
Vector3f x, y, z; // 3x1 float matrix.
RowVector3f a, b, c; // 1x3 float matrix.
VectorXd v1; // 双精度的动态列向量(Dynamic column vector of doubles)
//Eigen与matlab对应的关系
//// Eigen // Matlab // comments
//x.size(); // length(x) // 向量长度
//C.rows(); // size(C,1) // 行数
//C.cols(); // size(C,2) // 列数
//x(i); // x(i+1) // Matlab is 1-based
//C(i, j); // C(i+1,j+1) //
}
#include <iostream>
#include <Eigen\Dense>
using Eigen::MatrixXd;
using namespace std;
using namespace Eigen;
int main()
{
///动态矩阵初始化
MatrixXd m(2, 2);//MatrixXd 代表 这个矩阵是double类型, X代表具体的行数都动态编译的
m(0, 0) = 3;
m(1,