Search code examples
rlistfunctionapplycross-product

applying cross product (kronecker) many times


Suppose I have a list list0 of length D, where each element is a matrix N x T.

I am trying to create a Kronecker product, row by row that does the following.

for(i in 1:N){

    dummy[,i] <-  list0[[D]][i,] %x% ...( (list0[[2]][i,] %x% list0[[1]][i,]))

            }

Does anyone know the smartest way to apply this function? The below is an example where I manually type it out, but I want this for arbitrary D.

    set.seed(1)
    N = 2
    T = 3
    D = 4
    dummy = matrix(0,(T)^D,N)

    list0 = list()

    for(d in 1:D) {

        list0[[d]] <- matrix(rnorm(N*T,0,1),N,T)

            }

for(i in 1:N){

        dummy[,i] <-  list0[[4]][i,] %x% (list0[[3]][i,] %x% (list0[[2]][i,] %x% list0[[1]][i,]))

                }



   head(dummy)
            [,1]       [,2]
[1,]  0.15578313 -0.1783412
[2,]  0.20779959 -1.5492222
[3,] -0.08194020  0.7967800
[4,]  0.18402067  0.0737661
[5,]  0.24546573  0.6407946
[6,] -0.09679284 -0.3295669

Solution

  • The lapply gives a list of the ith row of the matrices and Reduce kroneckers them together. The sapply then assembles that into the final matrix.

    N <- nrow(list0[[1]])
    sapply(1:N, function(i) Reduce("%x%", init = 1, lapply(rev(list0), "[", i, TRUE)))