Friday, 23 April 2010

More efficient diag() function

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)
}
(c) Copyright 2008-2024 Mehmet Suzen (suzen at acm dot org)

Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License