function [x,sol]=spec_colloc_solve(N) % compute numerical solution to u''+u=0 with u(-1)=u(1)=1 using spectral % collocation % exact solution is u(x)=cos(x)/cos(1) % set up grid points and weights x=(cos((0:N)*pi/N))'; w=(-1).^(0:N); w(1)=1/2; w(end)=w(end)/2; % set up differentiation matrix D=zeros(N+1); for j=0:N for k=[0:j-1,j+1:N] D(j+1,k+1)=w(k+1)/w(j+1)/(x(j+1)-x(k+1)); end end for j=0:N D(j+1,j+1)=-sum(D(j+1,[1:j,j+2:N+1])); end % matrix representing operator L=D*D+eye(N+1); % apply boundary conditions u(-1)=1 and u(1)=1 L(1,:)=[1, zeros(1,N)]; L(N+1,:)=[zeros(1,N), 1]; rhs=zeros(N+1,1); rhs(1)=1; rhs(N+1)=1; % solve linear system sol=L\rhs; % compute norm of error err=norm(sol-cos(x)/cos(1),Inf) plot(x,sol)