编写Jacobi迭代法、Gauss-Seidel迭代法和SOR迭代法的M文件
时间: 2023-11-02 08:06:25 浏览: 189
下面是Jacobi迭代法、Gauss-Seidel迭代法和SOR迭代法的MATLAB代码示例:
1. Jacobi迭代法 (jacobi.m):
```matlab
function [x, iter] = jacobi(A, b, x0, tol, max_iter)
n = size(A, 1);
x = x0;
iter = 0;
while iter < max_iter
x_new = zeros(n, 1);
for i = 1:n
x_new(i) = (b(i) - A(i, [1:i-1, i+1:n]) * x([1:i-1, i+1:n])) / A(i, i);
end
if norm(x_new - x) < tol
break;
end
x = x_new;
iter = iter + 1;
end
if iter == max_iter
disp("Jacobi迭代法未收敛!");
end
end
```
2. Gauss-Seidel迭代法 (gauss_seidel.m):
```matlab
function [x, iter] = gauss_seidel(A, b, x0, tol, max_iter)
n = size(A, 1);
x = x0;
iter = 0;
while iter < max_iter
x_new = zeros(n, 1);
for i = 1:n
x_new(i) = (b(i) - A(i, 1:i-1) * x_new(1:i-1) - A(i, i+1:n) * x(i+1:n)) / A(i, i);
end
if norm(x_new - x) < tol
break;
end
x = x_new;
iter = iter + 1;
end
if iter == max_iter
disp("Gauss-Seidel迭代法未收敛!");
end
end
```
3. SOR迭代法 (sor.m):
```matlab
function [x, iter] = sor(A, b, x0, w, tol, max_iter)
n = size(A, 1);
x = x0;
iter = 0;
while iter < max_iter
x_new = zeros(n, 1);
for i = 1:n
x_new(i) = (1 - w) * x(i) + (w / A(i, i)) * (b(i) - A(i, [1:i-1, i+1:n]) * x_new([1:i-1, i+1:n]));
end
if norm(x_new - x) < tol
break;
end
x = x_new;
iter = iter + 1;
end
if iter == max_iter
disp("SOR迭代法未收敛!");
end
end
```
这些代码可以作为一个函数使用,传入系数矩阵A,右侧常数项b,初始解向量x0,容差tol和最大迭代次数max_iter。函数会返回迭代得到的解向量x以及迭代次数iter。
阅读全文