[R] add diagonal to matrix

arun smartpink111 at yahoo.com
Sun Aug 4 04:02:10 CEST 2013


This could be a bit faster.

x1<- matrix(NA,5,5)
diag(x1)<-0
x1[which(is.na(x1),arr.ind=TRUE)]<- as.vector(x)

#Speed comparison:
set.seed(585)
m1<- matrix(sample(1:40,4500*4499,replace=TRUE),ncol=4500)

system.time({
m2<- matrix(0,4500,4500)
indx<- which(m2==0,arr.ind=TRUE)
m2[indx[indx[,1]!=indx[,2],]]<- as.vector(m1)
})
#user  system elapsed 
#  3.304   0.616   3.927 


system.time({
m2New<- matrix(NA,4500,4500)
diag(m2New)<-0
m2New[which(is.na(m2New),arr.ind=TRUE)]<- as.vector(m1)
})
# user  system elapsed 
#  2.268   0.424   2.699 


system.time({
m3 <- matrix(0,4500,4500)
m3[upper.tri(m3)] <- m1[upper.tri(m1)]
m3[lower.tri(m3)] <- m1[lower.tri(m1, diag=TRUE)]
})
#user  system elapsed 
#  4.208   0.572   4.790 
identical(m2,m2New)
#[1] TRUE
 identical(m2,m3)
#[1] TRUE
A.K.




----- Original Message -----
From: arun <smartpink111 at yahoo.com>
To: Martin Batholdy <batholdy at googlemail.com>
Cc: R help <r-help at r-project.org>; Richard Heiberger <rmh at temple.edu>
Sent: Saturday, August 3, 2013 9:10 PM
Subject: 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.




More information about the R-help mailing list