In some circumstances, we might need to construct a matrix with a particular pattern. For instance, suppose we want to construct a matrix of the form
First we can create a matrix of the correct dimension
M <- matrix(0,10,10)
One way to proceed is to use a for loop
for (i in 1:10) {
M[i,i]<-1
if (i>1) M[i,i-1]<--1
if (i<10) M[i,i+1]<--1
}