I am solving the Poisson Equation for 2D given by the following expression: $$-\nabla\cdot (k(x,y) \nabla u)=f$$ in a rectangle with Dirichlet conditions on the boundary using Matlab. In principle I have made a code to solve the same problem, but in 1D and the code is as follows:
function [U,x]=p1d(n,alpha,beta,a,f)%alpha,beta, boundary conditions, here a is the k
x=linspace(0,1,n);x=x(:);
h=x(2)-x(1);
pm=(x(1:end-1)+x(2:end))/2;
K=diag(a(pm(1:end-1))+a(pm(2:end)))-diag(a(pm(2:end-1)),-1)-diag(a(pm(2:end-1)),1);
F=h.^2*f(x(2:n-1));
F(1)=F(1)+a(pm(1))*alpha;
F(n-2)=F(n-2)+a(pm(end))*beta;
U=K\F;
U=[alpha;U;beta];
endfunction
The problem I have to transfer the same ideas to 2D is the construction of the $K$ matrix. I understand how to add the conditions to the boundary, but the problem is that in the 2D case the position of each node is given by a strange shape, something like $l=(i-1)+(j-2)*(n-2)$.
By discretization, which is the following, using finite differences:
$-\Big(\dfrac{k_{i,j+\frac{1}{2}} u_{i,j+1}-\big(k_{i,j+\frac{1}{2}}+k_{i,j-\frac{1}{2}}\big)u_{i,j}+k_{i,j-\frac{1}{2}}u_{i,j-1}}{h^2}\Big)- \Big(\dfrac{k_{i+\frac{1}{2},j} u_{i+1,j}-\big(k_{i+\frac{1}{2},j}+k_{i-\frac{1}{2},j}\big)u_{i,j}+k_{i-\frac{1}{2},j}u_{i-1,j}}{h^2}\Big)=f_{i,j}$
you can see that the matrix is going to be diagonal by blocks, so the construction causes me problem.
Well what I started doing is the basics:
function U=poisson2d(x,y,k,f,g)% g condition to the border
n=size(x,1); % Mesh size
h=x(1,2)-x(1,1); %step size
K=sparse((n-2)*(n-2),(n-2)*(n-2)); %(this is the matrix causing me problem to assemble)
B=sparse((n-2)*(n-2),1);U=zeros(n); %initialize right side and solution
pmx=(x(:,1:end-1)+x(:,2:end))/2;%this is for the midpoints
pmy=(y(1:end-1,:)+x(2:end,:))/2;
Adding the input from the source function and the conditions to the boundary is no problem for me. But I can't implement the part of building K, I have a lot of trouble with the construction because of the position issue.
I hope you can help me, thank you in advance.
Edit
According to the discretization for the case of a 3x3 mesh, we would have the following coefficient matrix (not counting the boundary conditions). \begin{equation} \begin{pmatrix} \gamma & -\Gamma & 0 & -\Omega & 0 &0& 0& 0& 0\\ -\alpha & \gamma & -\Gamma& 0 &-\Omega& 0 &0& 0 &0\\ 0 & -\alpha & \gamma &0&0&-\Omega&0&0&0\\ -\beta &0 &0&\gamma&-\Gamma&0&-\Omega &0&0\\ 0&-\beta&0&-\alpha&\gamma&-\Gamma&0&-\Omega&0\\ 0&0&-\beta&0&-\alpha&\gamma&0&0&-\Omega\\ 0&0&0&-\beta&0&0&\gamma&\Gamma&0\\ 0&0&0&0&-\beta&0&-\alpha&\gamma&\Gamma\\ 0&0&0&0&0&-\beta&0&-\alpha&\gamma \end{pmatrix} \end{equation}
Where: $\gamma=\big(k_{i,j+\frac{1}{2}}+k_{i,j-\frac{1}{2}}+k_{i+\frac{1}{2},j}+k_{i-\frac{1}{2},j}\big)$
$\alpha=k_{i,j-\frac{1}{2}}$, $\Gamma =k_{i,j+\frac{1}{2}}$, $\beta=k_{i-\frac{1}{2},j}$, $\Omega=k_{i+\frac{1}{2},j}$
But why must the matrix be symmetric?