Skip to content
Prev 170395 / 398502 Next

Efficent way to create an nxn upper triangular matrix of one's

The other solutions offered are perfectly workable. Here is a strategy  
that is generalizable to other matrix designs (and on checking the  
source of upper.tri and lower.tri, it's not surprising that they use  
precisely the same strategy):

n <- 9
dm <- matrix(0, nrow=n, ncol=n)

dm[col(dm) >= row(dm)] <- 1

If you wanted only upper off-diagonal -1's, for instance, you could  
use instead:

dm[col(dm) == (row(dm)+1) ] <- -1