Creating nearest neighbors Laplacian matrix I want to create a general formula for an $N \times N$ nearest neighbors Laplacian matrix such that I can write an mfile in MATLAB to compute the matrix for given $N$.
The nearest neighbors Laplacian matrix is of the below form
\begin{equation}
L=\left[
\begin{array}{ccc}
-2 & 1 & 0 & \cdots & 0 & 1\\
1 & -2 & 1 & 0 & \cdots & 0\\
\vdots & \vdots & \vdots & \vdots & \vdots & \vdots \\
0 & \cdots & 0 & 1 & -2 & 1\\
1 & 0 & \cdots & 0 & 1 & -2\\
\end{array}
\right].
\end{equation} 
where the main diagonal elements are all $-2$ and we have two elements of $1$ before and after each element in the main diagonal.
Would appreciate any help...

I might be misreading what you have written as the $L$ matrix, but I believe you can use:
L = gallery('tridiag',ones(1,N-1),-2*ones(1,N),ones(1,N-1));
This will return the tridiaganol matrix in sparse form. You can wrap it in full() to convert it to a standard matrix. Then you can manually change the top and bottom corners to 1.
Let me know if this works or if I've misunderstood the form of L.
