Hi all, If I have a vector A<-1:6, I would like to convert A to an upper matrix M=[0 1 2 3 ; 0 0 4 5 ; 0 0 0 6; 0 0 0 0]. That is, if the length of the known vector is n, then the order m of the matrix I'd like to have should satisfy m(m-1)/2=n How could I do this in R? I really don't want to do it using a loop. Is there a function in R to do this ? Thanks! Best, Zhishi
Zhishi Wang wrote:> > Hi all, > > If I have a vector A<-1:6, I would like to convert A to an upper > matrix M=[0 1 2 3 ; 0 0 4 5 ; 0 0 0 6; 0 0 0 0]. > That is, if the length of the known vector is n, then the order m of > the matrix I'd like to have should satisfy m(m-1)/2=n > How could I do this in R? > I really don't want to do it using a loop. Is there a function in R to do > this ? >?upper.tri ?uniroot A <- 1:6 n <- length(A) m <- as.integer(uniroot(function(x) {x*(x-1)- 2*n}, c(1, n))$root) U <- matrix(0,nrow=m,ncol=m) U[upper.tri(U)] <- A U Berend -- View this message in context: http://r.789695.n4.nabble.com/how-to-convert-a-vector-to-an-upper-matrix-tp3587715p3587810.html Sent from the R help mailing list archive at Nabble.com.
Dear Berend, the coding is not working for more than 6. Try to plug 10 or other number. Would you please correct ? -- View this message in context: http://r.789695.n4.nabble.com/how-to-convert-a-vector-to-an-upper-matrix-tp3587715p4633628.html Sent from the R help mailing list archive at Nabble.com.
ozzi wrote> > Dear Berend, > > the coding is not working for more than 6. Try to plug 10 or other number. > Would you please correct ? >My mistake. mkupper <- function(A) { n <- length(A) m <- (1+sqrt(1+8*n))/2 stopifnot(m==as.integer(m)) print(m) L <- matrix(0,nrow=m,ncol=m) L[lower.tri(L)] <- A U <- t(L) U } A <- 1:6 mkupper(A) -- View this message in context: http://r.789695.n4.nabble.com/how-to-convert-a-vector-to-an-upper-matrix-tp3587715p4633630.html Sent from the R help mailing list archive at Nabble.com.