C++矩阵类设计与实现:高效、健壮的线性代数工具
在科学计算和工程应用中,矩阵运算是基础且关键的操作。本文将介绍一个完整的C++矩阵类实现,它支持常见的矩阵运算,包括加法、乘法、转置、行列式计算和逆矩阵求解。我们将深入探讨设计细节、实现技巧和性能优化。
矩阵类的数学基础
矩阵是线性代数中的核心概念,一个m×nm \times nm×n矩阵可以表示为:
A=[a11a12⋯a1na21a22⋯a2n⋮⋮⋱⋮am1am2⋯amn]A = \begin{bmatrix} a_{11} & a_{12} & \cdots & a_{1n} \\ a_{21} & a_{22} & \cdots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m1} & a_{m2} & \cdots & a_{mn} \end{bmatrix}A= a11a21⋮am1a12a22⋮am2⋯⋯⋱⋯a1na2n⋮amn
矩阵运算遵循特定的代数规则:
- 加法:C=A+BC = A + BC=A+B,其中cij=aij+bijc_{ij} = a_{ij} + b_{ij}cij=aij+bij
- 乘法:C=A×BC = A \times BC=A×B,其中cij=∑k=1naik×bkjc_{ij} = \sum_{k=1}^{n} a_{ik} \times b_{kj}cij=∑k=1naik×bkj
- 转置:B=ATB = A^TB=AT,其中bij=ajib_{ij} = a_{ji}bij=aji
- 行列式:仅方阵定义,记为det(A)\det(A)det(A)
- 逆矩阵:A−1A^{-1}A−1满足A×A−1=IA \times A^{-1} = IA×A−1=I
矩阵类完整实现
Matrix.h头文件
#pragma once
#include <vector>
#include <stdexcept>
#include <cmath>
#include <algorithm>
#include <utility>
#include <iostream>
#include <iomanip>
#include <initializer_list>class Matrix {
public:// 构造函数Matrix(int rows = 0, int cols = 0);Matrix(const std::vector<std::vector<double>>& data);Matrix(std::initializer_list<std::initializer_list<double>> list);// 五法则实现Matrix(const Matrix& other);Matrix(Matrix&& other) noexcept;Matrix& operator=(const Matrix& other);Matrix& operator=(Matrix&& other) noexcept;~Matrix() = default;// 元素访问运算符double& operator()(int i, int j);const double& operator()(int i, int j) const;std::vector<double>& operatorint i;const std::vector<double>& operatorint i const;// 矩阵运算Matrix operator+(const Matrix& other) const;Matrix operator-(const Matrix& other) const;Matrix operator*(const Matrix& other) const;Matrix operator*(double scalar) const;friend Matrix operator*(double scalar, const Matrix& matrix);// 特殊运算operator std::vector<std::vector<double>>() const { return _data; }Matrix transpose() const;double determinant() const;Matrix inverse() const;// 工具函数int rows() const { return _rows; }int cols() const { return _cols; }bool isSquare() const { return _rows == _cols; }void resize(int rows, int cols);void zero();void identity();double norm() const;void print(const std::string& title = "") const;// 静态工具函数static Matrix zeros(int rows, int cols);static Matrix ones(int rows, int cols);static Matrix eye(int n);private:std::vector<std::vector<double>> _data;int _rows, _cols;// 行列式计算辅助函数double determinantHelper(const Matrix& mat) const;
};