function exercise11task3 tol = 10^-12; nmax = 400; n=10; A=3* eye(n)-2* diag(ones(n-1,1),-1)- diag(ones(n-1,1),1); b=A*ones(n ,1); xx=ones(n,1); % Richardson k=1; x=zeros(n,1); while (k < nmax) && ~(norm(x(:,k)-xx) < tol) x(:,k+1) = (eye(n)- A)*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 400 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; 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 400 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; 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 400 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; 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 400 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--') legend('Richardson','Jacobi','forward Gauss-Seidel','backward Gauss-Seidel')