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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With