Eigen基本使用方法整理(持续更新)

Source

前言

最近在学习卡尔曼滤波,在矩阵的计算中我使用了C++ 的eigen库,这里将eigen库的基本函数记录下来,以供之后查阅。Eigen的官方说明文档链接

基本内容

数组转换为矩阵

下面的程序里将用到Eigen库中的几个函数这里先进行说明一下。

MatrixXd::Random(2,3); 生成一个double类型两行三列的矩阵。

test1.transpose();将矩阵test1转置;

MatrixXd test1 = Map < MatrixXd > (array, 3, 2);将数组array转换成三行两列的矩阵。这里先进行行后再进行列。 矩阵和array指向不同的内存空间,互不影响。

Matrix<double, 2, 3, ColMajor> test3 = Map< MatrixXd >(array, 2, 3);生成的矩阵主要是先排列再排行;

MatrixXd test4 = Map<Matrix<double, 2, 3, RowMajor>>(array);生成的矩阵主要是先排行再排列;

Map<Matrix<double, Dynamic, Dynamic, RowMajor>> test5(array,2,3); 动态矩阵的生成方法。

demo代码如下所示:

#include<iostream>
#include<Eigen/Dense>

using namespace std;
using namespace Eigen;

int main()
{
    
      
    MatrixXd test = MatrixXd::Random(2, 3);
    cout << test << endl;

    double *Mat = test.data();
    for(int i= 0;i<test.size();i++)
    {
    
      
        cout << "Mat [" <<i <<"]" << " is " << *(Mat+i) <<endl;
    }

    double array[] = {
    
      1, 2, 3, 4, 5, 6};
    MatrixXd test1 = Map<MatrixXd>(array, 3, 2); //先行后列
    cout <<"test1: " << endl << test1 << endl; 

    cout << "test2: " << endl << test1.transpose() <<endl; //转置

    Matrix<double, 2, 3, ColMajor> test3 = Map<MatrixXd>(array, 2, 3);

    cout << "test3: " << endl << test3 << endl;

    Matrix<double, 2, 3, RowMajor> test4 = Map<MatrixXd>(array, 2, 3);

    cout <<"test4: " <<endl << test4 <<endl;

    Map<Matrix<double, Dynamic, Dynamic, ColMajor>> test5(array, 2, 3);
    cout << "test5: " <<endl << test5 <<endl;
}

矩阵转换为数组

矩阵转换为数组的方法有如下两种:

① double * eigenMatptr = eigMat.data();

② double *eigMatptrnew = new double[eigMat.size()];
Map< MatrixXd>(eigMatptrnew, eigMat.rows(), eigMat.cols()) = eigMat;

注意的是在矩阵初始化的时候要正确的给出矩阵的维度然后再输入或者生成随机矩阵。

#include<iostream>
#include<Eigen/Dense>
using namespace std;
using namespace Eigen;

int main(int argc, char*argv[])
{
    
      
    Matrix3d eigmat;
    eigmat << 1, 2, 3,
              4, 5, 6,
              7, 8, 9;
    cout << eigmat <<endl;
    double* eigmatarry =eigmat.data();
    double* eigmatarrynew = new double[eigmat.size()];
    Map<MatrixXd>(eigmatarrynew, eigmat.rows(),eigmat.cols()) = eigmat;
    for(int i= 0;i<eigmat.size();i++)
    {
    
      

        cout <<"eigmatarrynew[" <<i <<"] is: " << *eigmatarrynew+i <<endl;
    }
    delete []eigmatarrynew;
}