Q:

Create a tridiagonal matrix

I need to program R with a matrix which has (1+x^2) down the leading diagonal (the constant value of x is given earlier in the program) and x down the diagonals on either side of the leading diagonal, and 0 everywhere else. I hope that makes sense! Can anyone tell me how I would program that, I can only find how to enter values on the leading diagonal and not any other diagonals. It is a 71x71 matrix so I cannot enter it manually!

A:

Scalar
If x is a scalar and n is the common row and column dimension then:
# test inputs
x <- 10
n <- 5

m <- diag(1+x^2, n)
m[abs(row(m) - col(m)) == 1] <- x

giving:
> m
     [,1] [,2] [,3] [,4] [,5]
[1,]  101   10    0    0    0
[2,]   10  101   10    0    0
[3,]    0   10  101   10    0
[4,]    0    0   10  101   10
[5,]    0    0    0   10  101

Vector
If x is a vector then since the sub-diagonal and super-diagonal are one element shorter than the diagonal we need to specify them separately -- here the latter two are specified as y.
# test values for diagonal and sub/super diagonals
x <- 1:5
y <- 11:14

m <- diag(x)
m[row(m) - col(m) == 1] <- m[row(m) - col(m) == -1] <- y

giving:
> m
     [,1] [,2] [,3] [,4] [,5]
[1,]    1   11    0    0    0
[2,]   11    2   12    0    0
[3,]    0   12    3   13    0
[4,]    0    0   13    4   14
[5,]    0    0    0   14    5

Note
Note that such a matrix is referred to as a tridiagonal matrix and searching for R tridiagonal will turn up some relevant links.

