function demo2 % *** Illustration of Assignment4, Problem 3 *** close all format compact set(0,'DefaultAxesFontSize',15) set(0,'DefaultAxesLinewidth',1) for n=round(logspace(1,8,100)) x=linspace(0,1,n+2)'; x=x(2:n+1); % *** Sparse system matrix *** A=spdiags([ones(n,1),-2*ones(n,1),ones(n,1)],-1:1,n,n); % *** Right hand side and reference solution *** rhs=2*(6*x.^2-1); yref=(n+1)^2*(x.^2.*(x-1).*(x+1)); % % *** Matlab backslash *** y=A\rhs; myerr1=norm(y-yref)/norm(yref); % % *** Solution based on matrix-vector multiplication with inverse *** k=[1:n]'; y=flipud(cumsum(k.*flipud(rhs))); y=-(flipud(k).*cumsum(k.*rhs)+k.*[y(2:n);0])/(n+1); myerr2=norm(y-yref)/norm(yref); % condA=(1+cos(pi/(n+1)))/(1-cos(pi/(n+1))) loglog(n,myerr1,'*',n,myerr2,'o',n,eps*condA,'d') title('Convergence with n') ylabel('Relative Error ||y-y_tilde||/||y||') xlabel('Number of points n') hl=legend('Backslash','Accurate inverse','eps*cond(A)','Location','North'); set(hl,'Fontsize',14) hold on grid on drawnow end