GNU R's diag() function provides a tool to produce diagonal matrices, however for
large vectors this is quite memory inefficient. Here is a version which uses at least
25% less memory;
mydiag<- function(A) {
#
# Given a a vector generate
# a diagonal matrix
# (Consume at least 1/4 less memory then R's diag)
#
A <- as.vector(A) ;
B <- matrix(0,nrow=length(A),ncol=length(A)) ;
row <- nrow(B) ;
col <- ncol(B) ;
size <- col*row ;
row <- row+1 ;
B[seq(1,size,row)] <- A ;
return(B)
}
No comments:
Post a Comment