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...

That symmetric matrix is almost a tridiagonal Toeplitz matrix. Hence,
r = [-2, 1, zeros(1,n-2)];
L = toeplitz(r);

Update now the northeast and southwest corners:
L(1,n) = 1;
L(n,1) = 1;

