As the title implies, how does one extract the sub- and superdiagonal of a matrix?
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
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.
来源:https://stackoverflow.com/questions/9885067/extract-sub-and-superdiagonal-of-a-matrix-in-r