[R] triangular matrices input/output

R. Michael Weylandt michael.weylandt at gmail.com
Thu May 17 01:41:36 CEST 2012


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:
> Hi,
>
> Is there any package that deals with triangular matrices?
>
> Say ways of inputting an upper (lower) triangular matrix?
>
> Or convert a vector of length 6 to an upper (lower) triangular matrix (by
> row/column)?
>
> Thanks!
>
> -----
> ######################
> PhD candidate in Statistics
> Big R Fan
> Big LEGO Fan
> Big sTaTs Fan
> ######################
>
> --
> View this message in context: http://r.789695.n4.nabble.com/triangular-matrices-input-output-tp4630310.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list