Extract sub- and superdiagonal of a matrix in R

邮差的信 提交于 2019-11-29 10:12:34

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!