Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading