I tried to implement the galerkin-method for the one dimensional poisson equation. I chose for the boundary conditions $$ u(0) = u(1) = 0 $$ and for the "source" term $f(x)$ $$ \frac{\partial^2 u(x)}{\partial x^2}=f(x) $$ $$f(x)=1$$ Now the problem is the solution, that I expected was $\frac{1}{2}*(x-0.5)^2-0.125$, instead I got the mirrored function around the x-axis, as if had picked $f(x)=-1$.
Below is my code where I generate the solution:
size = 1; % length of the interval
N = 10; % number of elements
K = N+1; % number of knots
h = size / N; % lenght of one element
A = zeros(K);
b = zeros(K, 1);
%initialize "stiffness" matrix and rhs
for i = 1:K
for j = 1:K
if(i==j)
A(i,j) = 2 / h;
elseif(abs(i-j)==1)
A(i,j) = -1 / h;
end
end
end
for i = 1:K
b(i) = h;
end
%remove first and last rows and columns, due to boundary condititons = 0
A(:,1) = [];
A(1,:) = [];
A(:,K-1) = [];
A(K-1,:) = [];
b = b(2:end-1)
%solve and add boundary values
y = [0;linsolve(A, b);0]
x = 0:h:1;
plot(x,y);
The values generated are right apart from the sign, is it an error produced by me or is it maybe even the correct solution, given my input conditions? I would be happy to hear any suggestions.
The equation which you attempt to solve in the code is $-u''=f$. Take care of the right signs when you do integration by parts to obtain the stiffness matrix.
In fact, the weak formulation of your PDE would read: $$a(u,v)=(f,v)$$
where $a(u,v)=-\int_0^1 u'v'$. If you put $u=v$ you see that the diagonal of your stiffness matrix should be negative, whereas yours is positive.
Summing up, your stiffness matrix has the wrong sign.