Extract sub- and superdiagonal of a matrix in R

a 夏天 提交于 2019-11-28 03:32:06

问题


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.



来源:https://stackoverflow.com/questions/9885067/extract-sub-and-superdiagonal-of-a-matrix-in-r

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