function exercise8task3 tol = 10^-12; nmax = 150; n=100; A=4* eye(n)-1* diag(ones(n-1,1),-1)- 2*diag(ones(n-1,1),1); b=A*ones(n ,1); xx=ones(n,1); % Richardson k=1; x=zeros(n,1); A1 = eye(n); A2 = A-A1; R = norm(A1\A2); % expected convergence rate while (k < nmax) && ~(norm(x(:,k)-xx) < tol) x(:,k+1) = -A2*x(:,k) + b; err(1,k+1) = norm(x(:,k+1)-xx); k=k+1; end K=k; display('Richardson method:') if k==nmax display('The tolerance was not reached after 150 steps. Check convergence!') else display('Number of steps needed:') k end display(' ') % Jacobi k=1; y=zeros(n,1); A1 = diag(diag(A)); A2 = A-A1; J = norm(A1\A2); % expected convergence rate while (k < nmax) && ~(norm(y(:,k)-xx) < tol) y(:,k+1) = A1\(b - A2*y(:,k)); err(2,k+1) = norm(y(:,k+1)-xx); k=k+1; end display('Jacobi method:') if k==nmax display('The tolerance was not reached after 150 steps. Check convergence!') else display('Number of steps needed:') k end display(' ') % Gauss-Seidel, forward k=1; z=zeros(n,1); A1 = tril(A); A2 = A-A1; GF = norm(A1\A2); % expected convergence rate while (k < nmax) && ~(norm(z(:,k)-xx) < tol) z(:,k+1) = A1\(b - A2*z(:,k)); err(3,k+1) = norm(z(:,k+1)-xx); k=k+1; end display('forward Gauss-Seidel method:') if k==nmax display('The tolerance was not reached after 150 steps. Check convergence!') else display('Number of steps needed:') k end display(' ') % Gauss-Seidel, backward k=1; w=zeros(n,1); A1 = triu(A); A2 = A-A1; GB = norm(A1\A2); % expected convergence rate while (k < nmax) && ~(norm(w(:,k)-xx) < tol) w(:,k+1) = A1\(b - A2*w(:,k)); err(4,k+1) = norm(w(:,k+1)-xx); k=k+1; end display('backward Gauss-Seidel method:') if k==nmax display('The tolerance was not reached after 150 steps. Check convergence!') else display('Number of steps needed:') k end %Plot S = size(err); semilogy(1:S(2),err(1,:),'b', 1:S(2),err(2,:),'g', 1:S(2),err(3,:),'r', 1:S(2),err(4,:),'k', 1:S(2),R.^(1:S(2)),'b:', 1:S(2),J.^(1:S(2)),'g:', 1:S(2),GF.^(1:S(2)),'r:', 1:S(2),GB.^(1:S(2)),'k:') legend('Richardson','Jacobi','forward Gauss-Seidel','backward Gauss-Seidel')