Quick Mastery of the Eigen Library from Scratch: A C++ Matrix Calculation Tool

1. Introduction to Eigen:

Eigen is an open-source C++ template library specifically designed for linear algebra operations, including matrices, vectors, numerical computations, and solving linear equations. It is known for its efficiency, supporting expression template optimizations to achieve near-optimal performance without runtime overhead. Eigen does not rely on third-party libraries and can be used simply by including its header files, making it a common tool in scientific computing and machine learning.

2. Installation and Configuration:

2.1 Installation on Linux

For Ubuntu/Debian systems:

sudo apt-get update
sudo apt-get install libeigen3-dev

2.2 CMake Project Configuration

cmake_minimum_required(VERSION 3.10)
project(MyEigenProject)
set(CMAKE_CXX_STANDARD 17)
# Find Eigen3 (version 3.3.0 and above)
find_package(Eigen3 REQUIRED)
# Recommended usage for modern CMake
add_executable(eigen_demo main.cpp)
target_link_libraries(eigen_demo Eigen3::Eigen)

3. Quick Start: Hello Eigen

Create main.cpp:

#include <iostream>
#include <Eigen/Dense>
int main() {
    // Create a 3x3 matrix
    Eigen::Matrix3d mat;
    // Comma initialization
    mat << 1, 2, 3,
           4, 5, 6,
           7, 8, 9;
    // Output the matrix
    std::cout << "=== Hello Eigen ===\n";
    std::cout << "Matrix:\n" << mat << "\n";
    // Basic operations
    std::cout << "\nTranspose:\n" << mat.transpose() << "\n";
    std::cout << "\nSum: " << mat.sum() << "\n";
    std::cout << "Determinant: " << mat.determinant() << "\n";
    return 0;
}

Compile and Run:

mkdir build && cd build
cmake ..
make
./eigen_demo

Output:

=== Hello Eigen ===
Matrix:
1 2 3
4 5 6
7 8 9
Transpose:
1 4 7
2 5 8
3 6 9
Sum: 45
Determinant: 0

4. Core Data Structures

4.1 Matrix Class

Static size matrices:

Eigen::Matrix<double, 3, 3> mat33;     // 3x3 double matrix
Eigen::Matrix<float, 4, 1> vec4;       // 4-dimensional float vector

Common predefined types:

Eigen::Matrix2d mat;    // 2x2 double
Eigen::Vector3f vec;    // 3-dimensional float vector
Eigen::RowVector4i rv;  // 4-dimensional int row vector

Dynamic size matrices:

Eigen::MatrixXd mat(10, 10);  // 10x10 double matrix
Eigen::VectorXf vec(100);     // 100-dimensional float vector

4.2 Array Class

Suitable for element-wise operations:

Eigen::ArrayXXf arr(3, 3);   // 3x3 float array
arr = arr.sqrt();            // Square root of each element
// Conversion to Matrix
Eigen::Matrix3f m = arr.matrix();  // Convert Array to Matrix

5. Initialization Methods

5.1 Basic Initialization

// Zero matrix
Eigen::Matrix3d zero_mat = Eigen::Matrix3d::Zero();
// Identity matrix
Eigen::Matrix4f identity = Eigen::Matrix4f::Identity();
// Constant matrix
Eigen::MatrixXd const_mat = Eigen::MatrixXd::Constant(5, 5, 2.5);
// Random matrix
Eigen::Matrix3f rand_mat = Eigen::Matrix3f::Random();

5.2 Advanced Initialization

// Linearly spaced vector
Eigen::VectorXd lin_vec = Eigen::VectorXd::LinSpaced(5, 0, 10);
// Initialize from C array
double data[] = {1,2,3,4,5};
Eigen::VectorXd vec = Eigen::Map<Eigen::VectorXd>(data, 5);
// Block operation initialization
Eigen::Matrix4f mat = Eigen::Matrix4f::Random();
Eigen::Matrix2f block_mat = mat.block<2,2>(1,1);  // Get 2x2 block starting from (1,1)

6. Common Operation Guide

6.1 Basic Operations

Eigen::Matrix3d A, B;
// Matrix addition and subtraction
Eigen::Matrix3d C = A + B;
// Matrix multiplication
Eigen::Matrix3d D = A * B;
// Dot product and cross product
double dot = v1.dot(v2);          // Dot product
Eigen::Vector3d cross = v1.cross(v2);  // Cross product

6.2 Matrix Operations

// Transpose and conjugate
mat.transpose();    // Transpose
mat.conjugate();    // Conjugate
// Determinant and trace
double det = mat.determinant();  // Determinant
double trace = mat.trace();      // Trace
// Matrix decomposition
Eigen::JacobiSVD<Eigen::MatrixXd> svd(mat);
Eigen::VectorXd singular_values = svd.singularValues();

6.3 Element Access

// Basic access
mat(i,j) = val;   // Access (i,j) element
vec[i] = val;     // Access vector element
// Row and column operations
mat.row(0) = v;   // Set first row
mat.col(1) = v;   // Set second column
// Diagonal elements
vec = mat.diagonal();  // Get diagonal elements

7. Practical Application Examples

7.1 Solving Linear Equations

Eigen::Matrix3f A;
Eigen::Vector3f b;
A << 1,2,3,
      4,5,6,
      7,8,10;
b << 3, 3, 4;
// Multiple methods of solving
Eigen::Vector3f x1 = A.lu().solve(b);        // LU decomposition
Eigen::Vector3f x2 = A.colPivHouseholderQr().solve(b);  // QR decomposition

7.2 Calculating Eigenvalues and Eigenvectors

Eigen::Matrix2f mat;
mat << 1, 2, 2, 3;
Eigen::SelfAdjointEigenSolver<Eigen::Matrix2f> solver(mat);
if (solver.info() == Eigen::Success) {
    auto eigenvalues = solver.eigenvalues();
    auto eigenvectors = solver.eigenvectors();
}

Eigen is a powerful tool for performing linear algebra operations in C++. Through this tutorial, you have mastered:

✅ Installation and configuration methods

✅ Core data structures and initialization

✅ Common matrix operations and manipulations

✅ Practical application examples

Next Issue Preview: Eigen in Practice – Implementation of Least Squares Method

After mastering the basics of Eigen, we will consolidate what we have learned through a practical project.

Supplementary references include Bilibili channels NoSharp, Man’s Contemplation, and 3Blue1Brown’s teaching videos, as well as tutorials from CSDN’s hongge_smile.

Leave a Comment