eigen详解

Eigen 是一个高性能的 C++ 数值计算库,特别擅长于矩阵和向量运算。Eigen 支持各种矩阵、向量操作,包括基本的线性代数运算、解方程、矩阵分解等。下面我将详细介绍 Eigen 的一些常见用法,并通过示例代码进行说明。

引入 Eigen 头文件

要使用 Eigen,需要包含它的头文件:

#include <Eigen/Dense>

创建矩阵和向量

Eigen 提供了 Matrix 和 Vector 类来创建矩阵和向量。可以指定矩阵或向量的大小和类型。

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

int main() {
    // 创建 3x3 矩阵
    Eigen::Matrix3d mat;
    mat << 1, 2, 3,
           4, 5, 6,
           7, 8, 9;
    std::cout << "Matrix:\n" << mat << std::endl;

    // 创建 3x1 向量
    Eigen::Vector3d vec;
    vec << 1, 2, 3;
    std::cout << "Vector:\n" << vec << std::endl;

    return 0;
}

基本矩阵运算

Eigen 支持矩阵的加法、减法、乘法、转置等操作。

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

int main() {
    Eigen::Matrix3d mat1;
    mat1 << 1, 2, 3,
            4, 5, 6,
            7, 8, 9;

    Eigen::Matrix3d mat2;
    mat2 << 9, 8, 7,
            6, 5, 4,
            3, 2, 1;

    // 矩阵加法
    Eigen::Matrix3d sum = mat1 + mat2;
    std::cout << "Sum:\n" << sum << std::endl;

    // 矩阵乘法
    Eigen::Matrix3d product = mat1 * mat2;
    std::cout << "Product:\n" << product << std::endl;

    // 矩阵转置
    Eigen::Matrix3d transpose = mat1.transpose();
    std::cout << "Transpose:\n" << transpose << std::endl;

    return 0;
}

解方程

Eigen 提供了多种方法来解线性方程组,例如使用 colPivHouseholderQr 分解。

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

int main() {
    Eigen::Matrix3d A;
    A << 1, 2, 1,
         2, 2, 3,
         3, 1, 2;

    Eigen::Vector3d b;
    b << 6, 14, 10;

    // 解 Ax = b
    Eigen::Vector3d x = A.colPivHouseholderQr().solve(b);
    std::cout << "Solution:\n" << x << std::endl;

    return 0;
}

矩阵分解

Eigen 支持多种矩阵分解方法,例如 LU 分解、QR 分解、SVD 分解等。

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

int main() {
    Eigen::Matrix3d A;
    A << 1, 2, 3,
         4, 5, 6,
         7, 8, 10;

    // LU 分解
    Eigen::FullPivLU<Eigen::Matrix3d> lu_decomp(A);
    Eigen::Matrix3d L = lu_decomp.matrixLU().triangularView<Eigen::Lower>();
    Eigen::Matrix3d U = lu_decomp.matrixLU().triangularView<Eigen::Upper>();

    std::cout << "L:\n" << L << std::endl;
    std::cout << "U:\n" << U << std::endl;

    return 0;
}

Eigen 还有许多高级功能,如稀疏矩阵运算、数值优化、自动微分等,可以根据需求深入学习和使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值