[R] add diagonal to matrix (sorry for having a little bug in last email)
Bin Yu
nkbinsos at hotmail.com
Sun Aug 4 04:40:55 CEST 2013
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.
More information about the R-help
mailing list