要使用C++矩阵类解决线性方程组,首先需要创建一个矩阵类,然后利用高斯消元法或其他数值方法求解线性方程组
#include<iostream>
#include<vector>
#include <cmath>
class Matrix {
public:
Matrix(int rows, int cols) : rows_(rows), cols_(cols), data_(rows * cols, 0) {}
double& operator()(int row, int col) {
return data_[row * cols_ + col];
}
const double& operator()(int row, int col) const {
return data_[row * cols_ + col];
}
int rows() const {
return rows_;
}
int cols() const {
return cols_;
}
private:
int rows_, cols_;
std::vector<double> data_;
};
void swap_rows(Matrix& matrix, int row1, int row2) {
for (int col = 0; col< matrix.cols(); ++col) {
std::swap(matrix(row1, col), matrix(row2, col));
}
}
void scale_row(Matrix& matrix, int row, double scale) {
for (int col = 0; col< matrix.cols(); ++col) {
matrix(row, col) *= scale;
}
}
void add_scaled_row(Matrix& matrix, int from_row, int to_row, double scale) {
for (int col = 0; col< matrix.cols(); ++col) {
matrix(to_row, col) += scale * matrix(from_row, col);
}
}
std::vector<double> gauss_jordan(Matrix matrix) {
int n = matrix.rows();
for (int i = 0; i < n; ++i) {
// 寻找主元
int max_row = i;
for (int k = i + 1; k < n; ++k) {
if (fabs(matrix(k, i)) > fabs(matrix(max_row, i))) {
max_row = k;
}
}
// 交换行
if (max_row != i) {
swap_rows(matrix, i, max_row);
}
// 消元
for (int j = i + 1; j < n; ++j) {
double scale = matrix(j, i) / matrix(i, i);
add_scaled_row(matrix, i, j, -scale);
}
}
// 回代求解
std::vector<double> result(n);
for (int i = n - 1; i >= 0; --i) {
result[i] = matrix(i, n);
for (int j = i + 1; j < n; ++j) {
result[i] -= matrix(i, j) * result[j];
}
result[i] /= matrix(i, i);
}
return result;
}
int main() {
// 定义线性方程组的系数矩阵和常数向量
Matrix A(3, 3);
A(0, 0) = 2; A(0, 1) = 3; A(0, 2) = 4;
A(1, 0) = 6; A(1, 1) = 7; A(1, 2) = 8;
A(2, 0) = 1; A(2, 1) = 5; A(2, 2) = 9;
Matrix b(3, 1);
b(0, 0) = 10;
b(1, 0) = 11;
b(2, 0) = 13;
// 合并系数矩阵和常数向量
Matrix Ab(A.rows(), A.cols() + 1);
for (int i = 0; i < A.rows(); ++i) {
for (int j = 0; j < A.cols(); ++j) {
Ab(i, j) = A(i, j);
}
Ab(i, A.cols()) = b(i, 0);
}
// 使用高斯消元法求解线性方程组
std::vector<double> x = gauss_jordan(Ab);
// 输出结果
std::cout << "Solution: ";
for (const auto& value : x) {
std::cout<< value << " ";
}
std::cout<< std::endl;
return 0;
}
这个例子中,我们创建了一个矩阵类,实现了高斯消元法,并使用它来求解一个线性方程组。你可以根据需要修改矩阵A和向量b来解决不同的线性方程组。