Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract sub- and superdiagonal of a matrix in R

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

like image 629
ego_ Avatar asked Mar 27 '12 07:03

ego_


2 Answers

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
like image 128
James Avatar answered Oct 18 '22 19:10

James


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.

like image 28
Andrew B. Avatar answered Oct 18 '22 18:10

Andrew B.