Skip to content
Prev 294812 / 398502 Next

triangular matrices input/output

The Matrix package provides good support for many special sorts of
matrices, but here it looks like you probably don't need that
additional machinery for such small case:

makeUpper <- function(vec, diag = FALSE){
    n <- (-1 + sqrt(1 + 8*length(vec)))/2
    stopifnot(isTRUE(all.equal(n, as.integer(n))))

    if(!diag) n <- n + 1

    mat <- matrix(0, ncol = n, nrow = n)
    mat[upper.tri(mat, diag)] <- vec
    mat
}

I think does what you want and it's not too hard to generalize to
lower triangular.

E.g.,

v <- 1:6
makeUpper(v)
makeUpper(v, diag = TRUE)

It's not super well tested though so caveat lector.

Michael
On Wed, May 16, 2012 at 5:09 PM, casperyc <casperyc at hotmail.co.uk> wrote: