# Optimizing finding the offset diagonals for a 2D Finite Difference Method

It is possible to collapse a conventional 2D PDE (in our case the Schrödinger equation) into one dimension by having each set of points be taken as a one dimensional list of $n$ lattice points and the Hamiltonian becomes a $n\times n$ matrix:

$$\sum_k\operatorname{H}_{ijk}\psi_k=\frac1{2h^2}(4\psi_{ij}-\psi_{i+1,j}-\psi_{i-1,j}-\psi_{i,j+1}-\psi_{i,j-1} )=\operatorname{E}\psi_{i,j}$$

This forms a mesh where each point looked at contributes -4 and all adjacent points contribute 1 in the respective place on the diagonal.

In the specific problem we have, certain points are removed from the grid (and so removed from the matrix). This means that the diagonals are unpredictable and so to find them I have made this function to find their coordinates:

isInside5[i_, coordlist_] :=  Block[{coord = Part[coordlist, i], output, a, length, itab},

a = List[coord + {1, 0}, coord - {1, 0}, coord + {0, 1}, coord - {0, 1}];
output = Intersection[a, coordlist];
length = Length[output];
itab = Table[{k, 1}, {k, 1, length}];
output = Insert[Table[
Part[Flatten[Position[coordlist, output[[k]]]]], {k, 1,
Length[output]}], i, itab]
]


This is currently the slowest part by far of the calculation. It takes a coordinate list of valid points [{x1,y1}, {x2,y2},...] and for each index i, finds the adjacent coordinates and checks if they are members of the coordinate list and then uses the position of these (their index) to generate a list of index coordinates so that they can be created in a sparse array to be set to 1.

Here is my hamiltonian function to see how it is used:

 hamiltonianarray3[coordlist_,parity_,xaxis_,yaxis_]:=
,offsetdiags,sqrt2coords,sqrt2diags, output},

diagonal=SparseArray[{i_,i_}->-4.,{lengthh,lengthh}];