function [x,U]=fin_diff_solve(N) % compute finite difference solution to u''+u=0 on uniform grid % with u(-1)=u(1)=1 % exact solution is u(x)=cos(x)/cos(1) % set up uniform grid h=2/N; x=-1:h:1; x=x(:); % set up finite difference matrix e=ones(N-1,1); A=spdiags([e -2*e e], -1:1, N-1, N-1); A=A/h^2; % set up right-hand-side b=zeros(N-1,1); b(1)=-1/h^2; b(N-1)=-1/h^2; % solve linear system U=(A+speye(N-1))\b; % add boundary data to U U=[1;U;1]; err=norm(U-cos(x)/cos(1),Inf) plot(x,U)