码迷,mamicode.com
首页 > 其他好文 > 详细

线性方程组的迭代解法——高斯-塞得勒迭代法

时间:2019-12-30 14:51:22      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:eth   线性   break   atl   elseif   lse   log   clear   初始   

  1.代码

%%高斯-塞得勒迭代法
%%线性方程组M*X = b,M是方阵,X0是初始解向量,epsilon是控制精度
function GSIM = Gauss_Seidel_iterative_method(M,b,X0,epsilon)
[m,n] = size(M);
d = diag(M); L = zeros(m,n); U = zeros(m,n); D = zeros(m,n);
ub = 100;X = zeros(m,ub);X(:,1) = X0;X_delta = X;X_end = zeros(m,1);k_end = 0;e = floor(abs(log(epsilon)));
for i = 1:m
    for j = 1:n
        if i > j
            L(i,j) = -M(i,j);
        elseif i < j
            U(i,j) = -M(i,j);
        elseif i == j
            D(i,j) = d(i);
        end
    end
end
B = (D-L)\U;
f = (D-L)\b;
for k = 1:ub-1
    X(:,k+1) = B*X(:,k)+f;
    X_delta(:,k) = X(:,k+1)-X(:,k);
    delta = norm(X_delta(:,k),2);
    if delta < epsilon
         break
    end
end
disp(‘迭代解及迭代次数为:‘);
k
GSIM = [X(:,k)‘];
end

  2.例子

clear all
clc
for i = 1:8
    for j = 1:8
        if i == j
            M(i,j) = 2.1;
        elseif i - j == 1
            M(i,j) = 1;
        elseif j - i == 1
            M(i,j) = -1;
        else
            M(i,j) = 0;
        end
    end
end
b = [1 2 3 4 4 3 2 1]‘;
X0 = [1 1 1 1 1 1 1 1]‘;
epsilon = 1e-4;

S = Gauss_Seidel_iterative_method(M,b,X0,epsilon)
M\b

  

线性方程组的迭代解法——高斯-塞得勒迭代法

标签:eth   线性   break   atl   elseif   lse   log   clear   初始   

原文地址:https://www.cnblogs.com/guliangt/p/12119337.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!