Extract sub- and superdiagonal of a matrix in R

2019-01-26 10:51发布

问题:

As the title implies, how does one extract the sub- and superdiagonal of a matrix?

回答1:

Using diag. For the superdiagonal, you just discard the last row and first column. For the subdiagonal, discard first row, last column:

m <- matrix(1:9,nrow=3)

> m
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
> diag(m)
[1] 1 5 9
> diag(m[-nrow(m),-1])
[1] 4 8
> diag(m[-1,-ncol(m)])
[1] 2 6


回答2:

You may need to reshape the results....

help(lower.tri)
help(upper.tri)
help(diag)

upper.tri and lower.tri do not include the diagonals.