Solves the linear system Ax=b iteratively by Jacobi method. Input arguments: A, square matrix b, column vector x0, initial estimate of the solution w, relaxation parameter ( w=1 gives unrelaxed iterations ) imax, maximum number of iterations Output arguments: x, solution k, number of iterations H, iteration matrix E, eigenvalues of the iteration matrix
0001 function [ x,k,H,E ] = Jacobi( A,b,x0,w,imax ) 0002 % Solves the linear system Ax=b iteratively by Jacobi method. 0003 % Input arguments: 0004 % A, square matrix 0005 % b, column vector 0006 % x0, initial estimate of the solution 0007 % w, relaxation parameter ( w=1 gives unrelaxed iterations ) 0008 % imax, maximum number of iterations 0009 % Output arguments: 0010 % x, solution 0011 % k, number of iterations 0012 % H, iteration matrix 0013 % E, eigenvalues of the iteration matrix 0014 0015 [m,n]=size(A); % find the size of A 0016 if n~= m 0017 error('input is not a square matrix'); 0018 elseif size(b,1)~=m; % check length of b 0019 error('input dimensions do not agree'); 0020 end 0021 0022 J=diag(diag(A)); % Set J to be the diagonal part of A 0023 B=A-J; % Set B to be the off-diagonal part of A 0024 temp=-B*x0+b; % calculate matrix vector product on right hand side 0025 for i=1:m; % solve diagonal system 0026 temp(i)=temp(i)/J(i,i); 0027 end 0028 x1=w*temp+(1-w)*x0; % implement relaxation 0029 k=1; % Set iteration counter to 1 0030 0031 while (abs(x1-x0)>1e-12) & (k <= imax); % convergence if the approximations 0032 % are close or the maximum number of 0033 % iterations is reached 0034 x0=x1; 0035 temp=-B*x0+b; % calculate matrix vector product on right hand side 0036 for i=1:m; % solve diagonal system 0037 temp(i,1)=temp(i)/J(i,i); 0038 end 0039 x1=w*temp+(1-w)*x0; % implement relaxation 0040 k=k+1; % increment counter 0041 end 0042 x=x1; 0043 0044 [H,E]=iteration_analysis(J,B,w); % this function calculates the iteration 0045 % matrix and its eigenvalues for 0046 % illustrative purposes. 0047 end 0048