function [x,k]=Jacobimethod(A,b,x0,N,emg)
% A:线性方程组左端矩阵
% b:线性没伍滚方程组右端向量
% x0:迭代初值
% N:迭橘肢代次数上界,若迭代枯余次数大于n,则迭代失败
% emg:精度指标
% k:迭代次数
% x:用迭代法求得的线性方程组的近似解
n=length(A)
x1=zeros(n,1)x2=zeros(n,1)
x1=x0k=0
r=max(abs(b-A*x1))
while r>emg
for i=1:n
sum=0
for j=1:n
if i~=j
sum=sum+A(i,j)*x1(j)
end
end
x2(i)=(b(i)-sum)/A(i,i)
end
r=max(abs(x2-x1))
x1=x2
k=k+1
if k>N
disp('迭代失败,返回');
return
end
end
祝朋友好运!
function [x, error, iter, flag] = jacobi(A, x, b, max_it, tol)% jacobi.m solves the linear system Ax=b using the Jacobi Method.
%
% input AREAL matrix
% xREAL initial guess vector
% bREAL right hand side vector
% max_it INTEGER maximum number of iterations
% tol REAL error tolerance
%
% output xREAL solution vector
% errorREAL error norm
% iter INTEGER number of iterations performed
% flag INTEGER: 0 = solution found to tolerance
% 1 = no convergence given max_it
iter = 0 % initialization
flag = 0
bnrm2 = norm( b )
if ( bnrm2 == 0.0 ), bnrm2 = 1.0end
r = b - A*x
error = norm( r ) / bnrm2
if ( error <好棚 tol ) return, end
[m,n]=size(A)
[ M, N ] = split( A , b, 1.0, 1 ) % matrix splitting
for iter = 1:max_it % begin iteration
x_1 = x
x = M \ (N*x + b) % update approximation
error = norm( x - x_1 ) /唤袜做 norm( x ) % compute error
if ( error <和衡= tol )
break
end % check convergence
end
if ( error >tol )
flag = 1
end % no convergence
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)