> x<-matrix(seq(1:16),4,4)
> x
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 4 8 12 16
How do I target all elements below the main diagonal and set them to 0, for a generic matrix, not just the example I provided?
You can do
x[lower.tri(x)] <- 0L
Another one:
x[row(x) > col(x)] <- 0L
(0L
, unlike 0
, is an integer. So using it here will preserve the class of your matrix.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With