# [R] Data Manipulation - make diagonal matrix of each element of a matrix

Clemontina Alexander ckalexa2 at ncsu.edu
Fri Dec 16 14:53:24 CET 2011

```Thank you, that is much simpler!

On Thu, Dec 15, 2011 at 2:04 PM, Rui Barradas <ruipbarradas at sapo.pt> wrote:
> Hello,
>
> I believe I can help, or at least, my code is simpler.
> First, look at your first line:
>
> idd <- length(diag(1,tt))   # length of intercept matrix
> #
> not needed: diag(tt) would do the job but it's not needed,
>    why call 2 functions, and one of them, 'diag', uses memory(*), if the
>    result is tt squared? It's much simpler!
>    (*)like you say, "larger and larger" amounts of it
>
> My solution to your problem is as follows (as a function, and yours).
>
> fun2 <- function(n, tt, numco){
>    M.Unit <- matrix(rep(diag(1,tt),n), ncol=tt, byrow=TRUE)
>    M <- NULL
>    for(i in 1:numco) M <- cbind(M, M.Unit*rep(x[,i], each=tt))
>    M
> }
>
> fun1 <- function(n, tt, numco){
>    idd <- length(diag(1,tt))    # length of intercept matrix
>    X <- matrix(numeric(n*numco*idd),ncol=tt*numco)
>    for(i in 1:numco){
>          X[,((i-1)*tt+1):(i*tt)] <- matrix(
>            c(matrix(rep(diag(1,tt),n),ncol=tt, byrow=TRUE))*
>                rep(rep(x[,i],each=tt),tt)
>           , ncol=tt)
>    }
>    X
> }
>
> I' ve tested the two with larger values of 'n', 'tt' and 'numco'
> using the following timing instructions
>
>
> n  <- 1000
> tt <- 50
> numco <- 15
> set.seed(1)
> x <- matrix(round(rnorm(n*numco),2), ncol=numco)   # the actual covariates
>
> Runs <- 10^1
>
> t1 <- system.time(for(i in 1:Runs) a1 <- fun1(n, tt, numco))[c(1,3)]
> t2 <- system.time(for(i in 1:Runs) a2 <- fun2(n, tt, numco))[c(1,3)]
>
> rbind(t1, t2, t1/t2)
>
>      user.self     elapsed
> t1 23.210000   31.060000
> t2 14.970000   22.540000
>     1.550434    1.377995
>
> As you can see, it's not a great speed improvement.
> I hope it's at least usefull.
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Data-Manipulation-make-diagonal-matrix-of-each-element-of-a-matrix-tp4200321p4201305.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help