雅可比(Jacobi)及高斯-塞德尔(Gauss_Seidel)迭代法求解线性方程组的matlab现实

雅可比迭代法的实现代码:

function X=Jacobi(A,B,P,delta,max1)
%Input -A is a X*N nosingular matrix
%     -B is a N*1 matrix
%     -P is a N*1 matrix ;the initial guess
%     _delta is the tolerance of P
%     -max1 is the maximum numbers of iterations
%Output -X is a N*1 matrix;the jacobi approximation to the solution of AX=B
N=length(B);
for i=1:max1
    %X(1)=(B(1)-A(1,2:N)*P(2:N))/A(1,1);
    for j=1:length(B)
        X(j)=(B(j)-(A(j,[1:j-1,j+1:N])*P([1:j-1,j+1:N])))/A(j,j);
    end
    err=abs(norm(X'-P));
    relerr=err/((norm(X)+eps));
    P=X';
    if err<delta||relerr<delta
        break;
    end
end

end

高斯-塞德尔迭代法的实现代码:

function X=Gseid(A,B,P,delta,max1)
%Input -A is a X*N nosingular matrix
%     -B is a N*1 matrix
%     -P is a N*1 matrix ;the initial guess
%     _delta is the tolerance of P
%     -max1 is the maximum numbers of iterations
%Output -X is a N*1 matrix;the jacobi approximation to the solution of AX=B
N=length(B);
for i=1:max1
    for j=1:length(B)
        if j==1
            X(1)=(B(1)-A(1,2:N)*P(2:N))/A(1,1);
        elseif j==N
            X(N)=(B(N)-A(N,1:N-1)*X(1:N-1)')/A(N,N);
        else
            X(j)=(B(j)-(A(j,1:j-1)*X(1:j-1)'+A(j,j+1:N)*P(j+1:N)))/A(j,j);
        end
    end
    err=abs(norm(X'-P));
    relerr=err/((norm(X)+eps));
    P=X';
    if err<delta||relerr<delta
        break;
    end
end

end

现在用的高斯-塞德尔迭代法小试牛刀:
在这里插入图片描述
求解的代码如下:

%creaet a 50*50 matrix A satisfing conditions
A=zeros(50,50);
A(1,1)=12;
A(1,2)=-2;
A(1,3)=1;

A(2,1)=-2;
A(2,2)=12;
A(2,3)=-2;
A(2,4)=1;
j=1;
for i=3:48
    A(i,j)=1;
    A(i,j+1)=-2;
    A(i,j+2)=12;
    A(i,j+3)=-2;
    A(i,j+4)=1;
    j=j+1;
end
A(49,47)=1;
A(49,48)=-2;
A(49,49)=12;
A(49,50)=-2;

A(50,48)=1;
A(50,49)=-2;
A(50,50)=12;
%creat a 50*1 matrix B 
B=5*ones(50,1);

求解结果如下:
1 至 13行

0.4638    0.5373    0.5090    0.4982    0.4989    0.5000    0.5001    0.5000    0.5000    0.5000    0.5000    0.5000    0.5000

14 至 26 行

0.5000    0.5000    0.5000    0.5000    0.5000    0.5000    0.5000    0.5000    0.5000    0.5000    0.5000    0.5000    0.5000

27 至 39 行

0.5000    0.5000    0.5000    0.5000    0.5000    0.5000    0.5000    0.5000    0.5000    0.5000    0.5000    0.5000    0.5000

40 至 50 行

0.5000    0.5000    0.5000    0.5000    0.5001    0.5000    0.4989    0.4982    0.5090    0.5373    0.4638
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值