-1

I know that with upper.tri() and lower.tri() I can get upper and lower triangular matrix divided by primary diagonal.

But what is the fastest way to get triangular matrix divided by the secondary diagonal?

Vadym B.
  • 681
  • 7
  • 21
  • What exactly do you mean by a matrix divided by the (secondary) diagonal (which is a vector)? Please edit your question, and provide an example of a matrix and what you want as output. – Anders Ellern Bilgrau Aug 13 '15 at 17:34
  • Secondary diagonal == antidiagonal == the diagonal going from top right to bottom left – A. Webb Aug 13 '15 at 17:40

2 Answers2

1

Just modify the code for lower.tri, e.g.

lower.anti.tri<-function(m) col(m)+row(m) > dim(m)[1]+1

m<-matrix(1:16,4)
lower.anti.tri(m)
      [,1]  [,2]  [,3]  [,4]
[1,] FALSE FALSE FALSE FALSE
[2,] FALSE FALSE FALSE  TRUE
[3,] FALSE FALSE  TRUE  TRUE
[4,] FALSE  TRUE  TRUE  TRUE
m[lower.anti.tri(m)]<-NA
m
     [,1] [,2] [,3] [,4]
[1,]    1    5    9   13
[2,]    2    6   10   NA
[3,]    3    7   NA   NA
[4,]    4   NA   NA   NA
A. Webb
  • 26,227
  • 1
  • 63
  • 95
0

You can use apply(mat, 1, rev) to horizontally flip a matrix so flipping lower.tri():

m <- matrix(1:16,4)
m[apply(lower.tri(m), 1, rev)] <- 0

m
#     [,1] [,2] [,3] [,4]
#[1,]    1    5    9   13
#[2,]    2    6   10    0
#[3,]    3    7    0    0
#[4,]    4    0    0    0
mattdevlin
  • 1,045
  • 2
  • 10
  • 17