Search code examples
rmatrixdiagonal

How to create a multi diagonal matrix in R


Hello I have this matrix that is (5 x 7)

enter image description here

and as you can see the matrix has three-diagonals from repeating numbers

I was wondering how to compute this matrix but for (t-2) x t dimension

I have this code, but only get the vector (of repeating numbers) in the diagonal (not 3 diagonal)

> diag(c(1,-2,1), nrow = 5, ncol=7)

     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    0    0    0    0    0    0
[2,]    0   -2    0    0    0    0    0
[3,]    0    0    1    0    0    0    0
[4,]    0    0    0    1    0    0    0
[5,]    0    0    0    0   -2    0    0

How can I accomplish this?

Thanks in advance


Solution

  • You can use toeplitz:

    mat <- toeplitz(c(1, -2, 1, 0, 0, 0, 0)) 
    mat[lower.tri(mat)] <- 0
    mat[1:5, ]
    
         [,1] [,2] [,3] [,4] [,5] [,6] [,7]
    [1,]    1   -2    1    0    0    0    0
    [2,]    0    1   -2    1    0    0    0
    [3,]    0    0    1   -2    1    0    0
    [4,]    0    0    0    1   -2    1    0
    [5,]    0    0    0    0    1   -2    1
    

    And, as a function (limited to dim > 3):

    m <- function(dim){
      vec = c(1, -2, 1, rep(0, dim - 3))
      mat <- toeplitz(vec)
      mat[lower.tri(mat)] <- 0
      mat[seq(dim - 2) , ]
    }
    
    > m(10)
         [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
    [1,]    1   -2    1    0    0    0    0    0    0     0
    [2,]    0    1   -2    1    0    0    0    0    0     0
    [3,]    0    0    1   -2    1    0    0    0    0     0
    [4,]    0    0    0    1   -2    1    0    0    0     0
    [5,]    0    0    0    0    1   -2    1    0    0     0
    [6,]    0    0    0    0    0    1   -2    1    0     0
    [7,]    0    0    0    0    0    0    1   -2    1     0
    [8,]    0    0    0    0    0    0    0    1   -2     1