Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a matrix, x, set all elements below the main diagonal to 0

Tags:

r

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

like image 443
Ben Avatar asked Mar 23 '23 07:03

Ben


1 Answers

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.)

like image 116
flodel Avatar answered Apr 06 '23 03:04

flodel