Eigen的基本用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35042020/article/details/83187525
#include <iostream>
#include <cmath>
using namespace std;
#include <ctime>
// Eigen 部分
#include <Eigen/Core>
// 稠密矩阵的代数运算(逆,特征值等)
#include <Eigen/Dense>
#include <Eigen/Geometry>

#define MATRIX_SIZE 50

int main(int argc, char** argv)
{
    /************矩阵向量声明***************/
    Eigen::Matrix<float, 3, 3> matrix_33;//3*3矩阵
    Eigen::Vector3d v_3d;//3*1向量,默认为double类型
    Eigen::Matrix<float, 4, 1> v_4d;//4*1向量
    Eigen::Matrix3d matrix3d = Eigen::Matrix3d::Zero(); //初始化3*3矩阵为零矩阵,默认为double类型

    Eigen::MatrixXd matrixXd; //动态矩阵声明
    matrixXd = Eigen::MatrixXd::Random(5,5);//动态矩阵变成5*5矩阵,默认为double类型

    /*矩阵数据输入*/
    v_3d << 1,2,3;
    v_4d << 1,2,3,4;
    matrix_33 << 1.0,-1.0,1.0, \
                 2.0,-2.0,2.0, \
                 -1.0,1.0,-1.0;

    /*矩阵数据打印*/
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++) {
            cout << matrix_33(i, j) << endl;
        }
    }

    /*矩阵运算*/
    // 但是在Eigen里你不能混合两种不同类型的矩阵,像以下代码是错的, Eigen::Vector3d v_3d 为double
    //Eigen::Matrix<double, 2, 1> result_wrong_type = matrix_23 * v_3d;
    Eigen::Matrix<double, 3, 1> result_right_type = matrix_33.cast<double>() * v_3d; //显示转换

    cout << "---------转置----------"<<endl;
    cout << matrix_33.transpose() << endl;      // 转置
    cout << "--------各元素和--------"<<endl;
    cout << matrix_33.sum() << endl;            // 各元素和
    cout << "----------迹-----------"<<endl;
    cout << matrix_33.trace() << endl;          // 迹
    cout << "----------数乘---------"<<endl;
    cout << 10 * matrix_33 << endl;             // 数乘
    cout << "-----------逆----------"<<endl;
    cout << matrix_33.inverse() << endl;        // 逆
    cout << "---------行列式---------"<<endl;
    cout << matrix_33.determinant() << endl;    // 行列式

    //Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigen_solver ( matrix_33.transpose()*matrix_33 );
    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eigen_solver ( matrix_33 );
    cout << "Eigen values = \n" << eigen_solver.eigenvalues() << endl;
    cout << "Eigen vectors = \n" << eigen_solver.eigenvectors() << endl;

    /*求解 matrix_nn * x = vector_nd 这个方程*/
    Eigen::Matrix<double, MATRIX_SIZE, MATRIX_SIZE> matrix_nn = Eigen::MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE);
    Eigen::Matrix<double, MATRIX_SIZE, 1>           vector_n1 = Eigen::MatrixXd::Random(MATRIX_SIZE, 1);

    // 直接求逆法
    Eigen::Matrix<double, MATRIX_SIZE, 1> x = matrix_nn.inverse() * vector_n1;
    // 通常用矩阵分解来求,例如QR分解,速度会快很多
    x = matrix_nn.colPivHouseholderQr().solve(vector_n1);
}

猜你喜欢

转载自blog.csdn.net/qq_35042020/article/details/83187525