雅可比迭代与高斯赛德尔迭 matlab 编码实现
function res = test(A, b, type)
max = 100;
level = 1;
[row, col] = size(A);
x_tmp = zeros(row, 1);
x = zeros(row, 1);
while 1
%使用雅可比迭代法
if strcmp(type, 'Jacobi')
x_tmp = Jacobi(A, b, row, col, x, x_tmp);
end
%使用高斯赛德尔迭代法
if strcmp(type, 'GauseSeidel')
x_tmp = GauseSeidel(A, b, row, col, x, x_tmp);
end
%判断是否在迭代精度范围内
if sum(abs(x_tmp)) - sum(abs(x)) < 0.000001
break;
end
x = x_tmp;
%计算迭代次数和监控线性方程组迭代是否为发散
level = level + 1;
if level > 100
break;
end
end
fprintf('使用的是 %s 迭代法\n', type);
if level > 100
fprintf('所求线性方程组迭代发散!\n');
else
fprintf('迭代次数为: %d\n', level);
fprintf('解得: \n');
for i = 1 : row
fprintf('\tx%d = %f\n', i, x(i));
end
end
%雅可比迭代
function x_tmp = Jacobi(A, b, row, col, x, x_tmp)
for i = 1 : row
x_tmp(i) = (b(i) - A(i,1:i-1)*x(1:i-1) - A(i,i+1:col)*x(i+1:end)) / A(i, i);
end
%高斯赛德尔迭代
function x_tmp = GauseSeidel(A, b, row, col, x, x_tmp)
for i = 1 : row
x_tmp(i) = (b(i) - A(i,1:i-1)*x_tmp(1:i-1) - A(i,i+1:col)*x(i+1:end)) / A(i, i);
end
测试数据
>> A
A =
4 -1 -1 0
-1 4 0 -1
-1 0 4 -1
0 -1 -1 4
>> b
b =
1
2
0
1
>> test(A, b, 'Jacobi')
使用的是 Jacobi 迭代法
迭代次数为: 21
解得:
x1 = 0.500000
x2 = 0.750000
x3 = 0.250000
x4 = 0.500000
>> test(A, b, 'GauseSeidel')
使用的是 GauseSeidel 迭代法
迭代次数为: 12
解得:
x1 = 0.500000
x2 = 0.750000
x3 = 0.250000
x4 = 0.500000
从中可以看出高斯赛德迭代法比雅可比迭代法的运算速度更快
Comments