R: Is there a simple and efficient way to return a matrix list of the building blocks of a block-diagonal matrix?

I'm looking for a function (inline) that efficiently returns a list of building blocks of a block-diagonal matrix like this (instead of iterating over slots to get the list manually):

#construct bdiag-matrix
library("Matrix")
listElems <- list(matrix(1:4,ncol=2,nrow=2),matrix(5:8,ncol=2,nrow=2))
mat <- bdiag(listElems)

#get back the list
res <- theFunctionImLookingFor(mat)

      

The result res

gives the building blocks:

[[1]]
      [,1] [,2]
[1,]    1    3
[2,]    2    4

[[2]]
      [,1] [,2]
[1,]    5    7
[2,]    6    8

      

Edit . As for my use case, the elements of the list in listElems

are square and symmetric matrices. If the block is a diagonal matrix, theFunctionImLookingFor

must return a list item for each diagonal item.

However, the function has to deal with block building matrices such as

       [,1] [,2] [,3]
[1,]    1    1    0
[2,]    1    1    1
[3,]    0    1    1

      

or

       [,1] [,2] [,3]
[1,]    1    0    1
[2,]    0    1    1
[3,]    1    1    1

      

i.e. deal with zeros in blocks that are not diagonal matrices.

+3


source to share


1 answer


Hope this works for all your cases, the test at the bottom contains a block containing zeros.

theFunctionImLookingFor <- function(mat, plot.graph = FALSE) {
   stopifnot(nrow(mat) == ncol(mat))
   x <- mat
   diag(x) <- 1
   edges <- as.matrix(summary(x)[c("i", "j")])
   library(igraph)
   g <- graph.edgelist(edges, directed = FALSE)
   if (plot.graph) plot(g)
   groups <- unique(Map(sort, neighborhood(g, nrow(mat))))
   sub.Mat <- Map(`[`, list(mat), groups, groups, drop = FALSE)
   sub.mat <- Map(as.matrix, sub.Mat)
   return(sub.mat)
}

listElems <- list(matrix(1:4,ncol=2,nrow=2),
                  matrix(5:8,ncol=2,nrow=2),
                  matrix(c(0, 1, 0, 0, 0, 1, 0, 0, 1),ncol=3,nrow=3),
                  matrix(1:1,ncol=1, nrow=1))

mat <- bdiag(listElems)

theFunctionImLookingFor(mat, plot.graph = TRUE)
# [[1]]
#      [,1] [,2]
# [1,]    1    3
# [2,]    2    4

# [[2]]
#      [,1] [,2]
# [1,]    5    7
# [2,]    6    8

# [[3]]
#      [,1] [,2] [,3]
# [1,]    0    0    0
# [2,]    1    0    0
# [3,]    0    1    1

# [[4]]
#      [,1]
# [1,]    1

      



enter image description here

+4


source







All Articles