要使用C++矩陣類解決線性方程組,首先需要創(chuàng)建一個矩陣類,然后利用高斯消元法或其他數(shù)值方法求解線性方程組
#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() {
// 定義線性方程組的系數(shù)矩陣和常數(shù)向量
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;
// 合并系數(shù)矩陣和常數(shù)向量
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);
// 輸出結(jié)果
std::cout << "Solution: ";
for (const auto& value : x) {
std::cout<< value << " ";
}
std::cout<< std::endl;
return 0;
}
這個例子中,我們創(chuàng)建了一個矩陣類,實現(xiàn)了高斯消元法,并使用它來求解一個線性方程組。你可以根據(jù)需要修改矩陣A和向量b來解決不同的線性方程組。