Tuesday, January 3, 2012

Create triangular matrices in R

Sometimes, you may want to use only the lower or upper triangular part of a (symmetric) matrix in R.


Lower triangular, without diagonal

lowtri <- function(matr) {
lt <- matrix(NA,nr=nrow(matr),nc=ncol(matr))
for (i in 2:(nrow(lt))) {
for (j in 1:(i-1)) {
lt[i,j] <- abs(matr[i,j])
}
}
print(lt)
}

Lower triangular, with diagonal

lowtri <- function(matr) {
lt <- matrix(NA,nr=nrow(matr),nc=ncol(matr))
for (i in 1:(nrow(lt))) {
for (j in 1:i) {
lt[i,j] <- abs(matr[i,j])
}
}
print(lt)
}

Lower triangular, without diagonal

uptri <- function(matr) {
ut <- matrix(NA,nr=nrow(matr),nc=ncol(matr))
for (i in 1:(nrow(ut)-1)) {
for (j in (i+1):nrow(ut)) {
ut[i,j] <- abs(matr[i,j])
}
}
print(ut)
}

Upper triangular, with diagonal

uptri <- function(matr) {
ut <- matrix(NA,nr=nrow(matr),nc=ncol(matr))
for (i in 1:nrow(ut)) {
for (j in i:nrow(ut)) {
ut[i,j] <- abs(matr[i,j])
}
}
print(ut)
}

2 comments:

  1. Thank you for your posting :) It's really easy and powerful. I like your codes in this blog.

    ReplyDelete
  2. You're welcome! Thanks for your comment!

    ReplyDelete