matrix - How does one get the kth diagonal in R? What about the "opposite" diagonals? -


this question has answer here:

suppose have square matrix:

x<-matrix(sample(36),ncol=6) 

in matlab, diag function has convenient argument k getting "non-central" diagonals of x. what's simplest way in r?

secondly, how 1 same "up-right" instead of standard "down-left" diagonals?

mat = matrix(c(1:25), nrow = 5, ncol = 5, byrow = true) mat      [,1] [,2] [,3] [,4] [,5] [1,]    1    2    3    4    5 [2,]    6    7    8    9   10 [3,]   11   12   13   14   15 [4,]   16   17   18   19   20 [5,]   21   22   23   24   25  # diagonal mat[row(mat) == col(mat)] [1]  1  7 13 19 25  # "lower" diagonals mat[row(mat) == col(mat)+1] [1]  6 12 18 24 > mat[row(mat) == col(mat)+2] [1] 11 17 23  # "upper" diagonals mat[row(mat) == col(mat)-1] [1]  2  8 14 20 mat[row(mat) == col(mat)-2] [1]  3  9 15 

... @benbolker's answer (of course) more elegant.

it looks ben deleted answer, i'll post slight modification of here. assuming k number of places above main diagonal, then:

mat[col(mat) - row(mat) == k] 

will give diagonal k places above main diagonal if k positive , below if k negative.

per @michaelchirico's comment, "up-to-the-right" diagonals:

mat[row(mat) + col(mat) == m] 

where 2 <= m <= 2*nrow(mat).


Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -