雅可比迭代法的实现代码:
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