[R] add diagonal to matrix

arun smartpink111 at yahoo.com
Sun Aug 4 03:10:15 CEST 2013


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