% finite element solution of u''+u=-x,u(0)=u(1)=0
% linear elements
% MDG 1/4/13
N=5; %no basis functions phi_0 or phi_N so here N only includes interior elements
h=1/(N+1); %N+1 here corresponds to N in the book
A=zeros(N,N);
u=zeros(N,1);
x1=(0:h:1)';
b=zeros(N,1);
A(1,1)=2/3 *h-2/h;
A(2,1)=h/6+1/h;
A(N,N)=2/3 *h-2/h;
A(N-1,N)=h/6+1/h;
for i=2:N-1
A(i,i)=2/3 *h-2/h;
A(i-1,i)=h/6+1/h;
A(i+1,i)=h/6+1/h;
end
for i=1:N
b(i)=-i*h^2;
end
u= A \ b;
us=zeros(N+2,1); %vector of solution values including boundaries
us(1)=0;
us(N+2)=0;
for i=1:N
us(i+1)=u(i);
end
us1 = us;
% exact solution
Nex=100;
hex=1/(Nex+1);
uex=zeros(Nex+2,1);
xex=0:hex:1;
uex=-xex+sin(xex)*csc(1);
N=11; %repeat but with larger N
h=1/(N+1);
A=zeros(N,N);
u=zeros(N,1);
x2=(0:h:1)';
b=zeros(N,1);
A(1,1)=2/3 *h-2/h;
A(2,1)=h/6+1/h;
A(N,N)=2/3 *h-2/h;
A(N-1,N)=h/6+1/h;
for i=2:N-1
A(i,i)=2/3 *h-2/h;
A(i-1,i)=h/6+1/h;
A(i+1,i)=h/6+1/h;
end
for i=1:N
b(i)=-i*h^2;
end
u = A \ b;
us=zeros(N+2,1); %vector of solution values including boundaries
us(1)=0;
us(N+2)=0;
for i=1:N
us(i+1)=u(i);
end
us2 = us;
plot(xex, uex, '-', x1, us1, '-.', x2, us2,'--')
legend('Exact','N=6','N=12')
t1 = [xex', uex']; t2 = [x1, us1]; t3=[x2, us2];
save "FEGalerkin1.dat" t1 t2 t3