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?
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?
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
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