帮我写一个求解Ax=b的C++函数代码,该函数是矩阵类中的成员函数
时间: 2023-12-27 22:02:45 浏览: 68
好的,下面是一个求解Ax=b的C++函数代码,该函数是矩阵类中的成员函数:
```c++
#include <iostream>
#include <vector>
using namespace std;
class Matrix {
private:
int rows, cols;
vector<vector<double>> data;
public:
Matrix(int r, int c) : rows(r), cols(c), data(vector<vector<double>>(r, vector<double>(c))) {}
void set(int i, int j, double val) {
data[i][j] = val;
}
void print() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << data[i][j] << " ";
}
cout << endl;
}
}
vector<double> solve(vector<double>& b) {
if (rows != cols || rows != b.size()) {
throw "Invalid input!";
}
vector<vector<double>> A(rows, vector<double>(cols + 1));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
A[i][j] = data[i][j];
}
A[i][cols] = b[i];
}
for (int i = 0; i < rows; i++) {
int pivot = i;
for (int j = i + 1; j < rows; j++) {
if (abs(A[j][i]) > abs(A[pivot][i])) {
pivot = j;
}
}
if (pivot != i) {
swap(A[i], A[pivot]);
}
for (int j = i + 1; j <= cols; j++) {
A[i][j] /= A[i][i];
}
for (int j = i + 1; j < rows; j++) {
for (int k = i + 1; k <= cols; k++) {
A[j][k] -= A[j][i] * A[i][k];
}
}
}
vector<double> x(cols);
for (int i = cols - 1; i >= 0; i--) {
x[i] = A[i][cols];
for (int j = i + 1; j < cols; j++) {
x[i] -= A[i][j] * x[j];
}
}
return x;
}
};
int main() {
Matrix A(3, 3);
A.set(0, 0, 2);
A.set(0, 1, -1);
A.set(0, 2, 0);
A.set(1, 0, -1);
A.set(1, 1, 2);
A.set(1, 2, -1);
A.set(2, 0, 0);
A.set(2, 1, -1);
A.set(2, 2, 2);
vector<double> b{1, 2, 3};
try {
vector<double> x = A.solve(b);
for (int i = 0; i < x.size(); i++) {
cout << "x" << i + 1 << " = " << x[i] << endl;
}
} catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
```
这个函数使用了高斯-约旦消元法来求解Ax=b,其中A是一个矩阵,b是一个列向量,x是一个列向量,表示方程组Ax=b的解。在代码中,我们首先将A和b组合成一个增广矩阵,然后使用高斯-约旦消元法将其化为行阶梯形式,最后通过回带法求解x。
阅读全文