Eigen常用代码

3 篇文章 0 订阅

转载:https://blog.csdn.net/jjjwwwjjjwww/article/details/63684684

#include <iostream>
using namespace std;

#include <Eigen/Core>
#include <Eigen/Dense>

int main( )
{
    // 矩阵类模板的前三个参数为:数据类型,行,列
    Eigen::Matrix< float, 2, 3 > matrix_23;
    // 填充数据
    matrix_23 << 1, 2, 3, 4, 5, 6;
    // 输出:
    // 1 2 3
    // 4 5 6
    cout << matrix_23 << endl;
    // 访问元素
    // 输出:
    // 1
    // 2
    for ( int i = 0; i < 1; i++ )
        for ( int j = 0; j < 2; j++ )
            cout << matrix_23( i, j ) << endl;

    // Vector3d实质上是Eigen::Matrix< double, 3, 1 >
    Eigen::Vector3d v_3d;
    v_3d << 3, 2, 1;

    // 矩阵和向量相乘,但不允许混合类型
    Eigen::Matrix< double, 2, 1 > result = matrix_23.cast< double >( ) * v_3d;
    // 输出:
    // 10
    // 28
    cout << result << endl;

    Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Zero( );
    matrix_33 = Eigen::Matrix3d::Random( );
    cout << matrix_33 << endl;

    cout << matrix_33.transpose( ) << endl;
    cout << matrix_33.sum( ) << endl;  // 各元素和
    cout << matrix_33.trace( ) << endl;
    cout << 10 * matrix_33 << endl;  // 数乘
    cout << matrix_33.inverse( ) << endl;  // 逆
    cout << matrix_33.derterminant( ) << endl;

    // 特征值
    Eigen::SelfAdjointEigenSolver< Eigen::Matrix3d > eigen_solver( matrix_33 );
    cout << "Eigen values = " << eigen_solver.eigenvalues( ) << endl;
    cout << "Eigen vectors = " << eigen_solver.eigenvectors( ) << endl;

    // 解方程
    // matrix_33 * x = v_3d
    // 直接求逆(运算量大)
    Eigen::Vector3d x = matrix_33.inverse( ) * v_3d;
    cout << "x = " << x << endl;
    // 矩阵分解法,如QR分解
    x = matrix_33.colPivHouseholderQr( ).solve( v_3d );
    cout << "x = " << x << endl;

    // 若不确定矩阵大小,可以使用动态大小的矩阵
    Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > matrix_dynamic;

    Eigen::MatrixXd matrix_x;
    return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值