0

Suppose I have a square matrix:

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

In MATLAB, the diag function has a convenient argument k for getting "non-central" diagonals of x. What's the simplest way to do this in R?

Secondly, how would one do the same to get the "up-right" instead of the standard "down-left" diagonals?

MichaelChirico
  • 33,841
  • 14
  • 113
  • 198

1 Answers1

4
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

... but @BenBolker's answer is (of course) more elegant.

It looks like Ben deleted his answer, so I'll post a slight modification of it here. Assuming k is the number of places above the main diagonal, then:

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

will give you the diagonal k places above the main diagonal if k is positive and below if k is negative.

Per @MichaelChirico's comment, to get the "up-to-the-right" diagonals:

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

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

eipi10
  • 91,525
  • 24
  • 209
  • 285
  • Thanks. never heard of the `row` functions, so this also extends easily to getting the "up-right" diagonals instead of the "down-left" diagonals. – MichaelChirico Jun 03 '15 at 22:30
  • might as well edit that into the answer--I'll add this bit to the question, which should distinguish it as unique from the question @BenBolker referenced – MichaelChirico Jun 03 '15 at 22:43