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

Another way of doing this for full matrices is:
>> N=5;
>> L=diag(-2*ones(1,N),0)+diag(ones(1,N-1),1)+diag(ones(1,N-1),-1)
L =

  -2   1   0   0   0
   1  -2   1   0   0
   0   1  -2   1   0
   0   0   1  -2   1
   0   0   0   1  -2

>> L(1,N)=1
L =

  -2   1   0   0   1
   1  -2   1   0   0
   0   1  -2   1   0
   0   0   1  -2   1
   0   0   0   1  -2

>> L(N,1)=1
L =

  -2   1   0   0   1
   1  -2   1   0   0
   0   1  -2   1   0
   0   0   1  -2   1
   1   0   0   1  -2

>>

