Bin Yu
2013-Aug-04 02:40 UTC
[R] add diagonal to matrix (sorry for having a little bug in last email)
Hi, I have another method: set.seed(48) n <- 4500 m1 <- matrix(sample(1:40,n*(n-1),replace=TRUE),ncol=n) m2 <- vector("numeric",length=n^2) system.time({m2[!seq_along(m2)%in%seq.int(n)^2] <- as.vector(m1);m3<-array(m2,dim=c(n,n))}) # user system elapsed # 1.62 0.39 2.04 Best Regards! Fechy ----- Original Message ----- ???: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] ?? arun ????: 2013?8?4? 9:10 ???: Martin Batholdy ??: R help ??: Re: [R] add diagonal to matrix You could also try: x1<-matrix(0,5,5) indx<-which(!is.na(x1),arr.ind=TRUE) x1[indx[indx[,1]!=indx[,2],]]<- as.vector(x) #Speed comparison: set.seed(48) m1<- matrix(sample(1:40,4500*4499,replace=TRUE),ncol=4500) m2<- matrix(0,4500,4500) system.time({ indx<- which(m2==0,arr.ind=TRUE) m2[indx[indx[,1]!=indx[,2],]]<- as.vector(m1) }) # user system elapsed # 3.376 0.648 4.037 m3 <- matrix(0,4500,4500) system.time({ m3[upper.tri(m3)] <- m1[upper.tri(m1)] m3[lower.tri(m3)] <- m1[lower.tri(m1, diag=TRUE)] }) # user system elapsed # 4.236 0.460 4.709 identical(m2,m3) #[1] TRUE A.K. ----- Original Message ----- From: Martin Batholdy <batholdy at googlemail.com> To: "r-help at r-project.org" <r-help at r-project.org> Cc: Sent: Saturday, August 3, 2013 2:54 PM Subject: [R] add diagonal to matrix Hi, I have a 5 columns x 4 rows matrix and would like to add a diagonal of zeros so that I end up with a 5x5 matrix. x <- matrix(1:20, 4,5) what is the easiest way to accomplish this in R? thanks for any suggestions! ______________________________________________ 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. ______________________________________________ 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.