Hello,

I needed this once.

upper.diag <- function(x, byrow=FALSE){
        m <- sqrt(1 + 8*length(x))
        if(abs(m - floor(m)) <  .Machine$double.eps^0.5)
                m <- (m - 1)/2
        else{
                warning("length of 'x' is not a triangular number.")
                m <- floor((m - 1)/2)
        }
        y <- matrix(0, nrow=m, ncol=m)
        if(byrow){
                y[lower.tri(y, TRUE)] <- x
                y <- t(y)
        }else
                y[upper.tri(y, TRUE)] <- x
        y
}

lower.diag <- function(x, byrow=FALSE){
        m <- sqrt(1 + 8*length(x))
        if(abs(m - floor(m)) <  .Machine$double.eps^0.5)
                m <- (m - 1)/2
        else{
                warning("length of 'x' is not a triangular number.")
                m <- floor((m - 1)/2)
        }
        y <- matrix(0, nrow=m, ncol=m)
        if(byrow){
                y[upper.tri(y, TRUE)] <- x
                y <- t(y)
        }else
                y[lower.tri(y, TRUE)] <- x
        y
}

lower.diag(1:6)
lower.diag(1:10, TRUE)
lower.diag(1:8)

upper.diag(1:6)
upper.diag(1:10, TRUE)
upper.diag(1:12)

Hope this helps,

Rui Barradas

casperyc 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@ 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.
> 


--
View this message in context: 
http://r.789695.n4.nabble.com/triangular-matrices-input-output-tp4630322p4630328.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
R-help@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.

Reply via email to