用matlab实现一下
时间: 2023-07-20 20:36:15 浏览: 58
好的,让我们用MATLAB实现一下高斯消元法和Gauss-Seidel迭代法来解决线性方程组。
首先,我们可以定义一个函数,将线性方程组转化为增广矩阵形式:
```
function [aug] = aug_mat(A, b)
% Convert a linear system Ax=b to the augmented matrix [A|b]
n = size(A, 1);
aug = [A, b];
end
```
接下来,我们可以定义一个函数,使用高斯消元法将增广矩阵转化为行简化阶梯形式,并返回解向量:
```
function [x] = gauss_elim(A, b)
% Solve a linear system Ax=b using Gaussian elimination
% Convert to augmented matrix form
aug = aug_mat(A, b);
% Forward elimination
n = size(A, 1);
for k = 1:n-1
for i = k+1:n
factor = aug(i,k) / aug(k,k);
aug(i,k:end) = aug(i,k:end) - factor*aug(k,k:end);
end
end
% Back substitution
x = zeros(n, 1);
x(n) = aug(n,n+1) / aug(n,n);
for i = n-1:-1:1
x(i) = (aug(i,n+1) - aug(i,i+1:n)*x(i+1:n)) / aug(i,i);
end
end
```
现在,我们可以使用高斯消元法来解决线性方程组,例如:
```
% Define the coefficient matrix and the right-hand side vector
A = [3, 2, -1; 2, -2, 4; -1, 0.5, -1];
b = [1; -2; 0];
% Solve the linear system using Gaussian elimination
x = gauss_elim(A, b);
% Output the solution
disp(x);
```
这将输出解向量[0, -1, 1]。
接下来,我们可以定义一个函数,使用Gauss-Seidel迭代法来解决线性方程组:
```
function [x] = gauss_seidel(A, b, tol, max_iter)
% Solve a linear system Ax=b using Gauss-Seidel iteration
% Decompose the coefficient matrix A
D = diag(diag(A));
L = tril(A) - D;
U = triu(A) - D;
% Initialize the solution vector
n = size(A, 1);
x = zeros(n, 1);
% Iterate until convergence or max_iter
iter = 0;
error = Inf;
while error > tol && iter < max_iter
x_prev = x;
for i = 1:n
x(i) = (b(i) - L(i,:)*x - U(i,:)*x_prev) / D(i,i);
end
error = norm(x - x_prev) / norm(x);
iter = iter + 1;
end
end
```
现在,我们可以使用Gauss-Seidel迭代法来解决同样的线性方程组,例如:
```
% Define the coefficient matrix and the right-hand side vector
A = [3, 2, -1; 2, -2, 4; -1, 0.5, -1];
b = [1; -2; 0];
% Solve the linear system using Gauss-Seidel iteration
x = gauss_seidel(A, b, 1e-6, 100);
% Output the solution
disp(x);
```
这将输出与高斯消元法相同的解向量[0, -1, 1]。
阅读全文