gauss-seidel迭代法 matlab完整代码 % A为线性方程组的系数矩阵 A=[10 -2 -1;-2 10 -1;-1 -2 5]; % b为常系数 x为初始向量 b=[0;-21;-20]; x=[1;1;1];
时间: 2024-12-20 21:28:13 浏览: 9
Gauss-Seidel迭代法是一种用于求解线性方程组的数值解法,它通过迭代的方式逐步逼近真实解。以下是使用Matlab编写的一个简单Gauss-Seidel迭代算法的例子:
```matlab
function [solution, iterations] = gauss_seidel(A, b, x0, tol, max_iterations)
n = size(A, 1); % 获取矩阵维度
solution = x0;
iterations = 0;
% Gauss-Seidel循环
while true
old_solution = solution;
% 更新当前行元素
for i = 1:n
sum = 0;
for j = 1:i-1
sum = sum + A(i,j) * solution(j);
end
if i < n
sum = sum + A(i,i) * solution(i);
end
solution(i) = (b(i) - sum) / A(i,i);
end
% 检查收敛条件
diff = norm(solution - old_solution, 'inf');
iterations = iterations + 1;
if diff < tol || iterations >= max_iterations
break;
end
end
% 输出结果
solution;
end
% 定义矩阵、常数项、初始猜测值以及容差和最大迭代次数
A = [10 -2 -1; -2 10 -1; -1 -2 5];
b = [0; -21; -20];
x0 = ones(3, 1); % 初始化向量全为1
tol = 1e-6; % 容错阈值
max_iterations = 100; % 最大迭代次数
[x, num_iters] = gauss_seidel(A, b, x0, tol, max_iterations);
disp(['Solution after convergence: ' num2str(x)]);
disp(['Number of iterations: ' num2str(num_iters)]);
%
阅读全文