R:是否有一种简单有效的方法来获取块对角矩阵的构建块矩阵列表? [英] R: Is there a simple and efficient way to get back the list of building block matrices of a block-diagonal matrix?

查看:232
本文介绍了R:是否有一种简单有效的方法来获取块对角矩阵的构建块矩阵列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个(内置)函数,该函数可以通过以下方式有效地返回块对角矩阵的构建块列表(而不是遍历插槽以手动获取列表):

I'm looking for a (build-in) function, which efficiently returns the list of building blocks of a block-diagonal matrix in the following way (rather than iterating over the 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)

结果res产生了构建基块:

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

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

编辑:关于我的用例,listElems中的列表元素是正方形和对称矩阵.如果块是对角矩阵,则theFunctionImLookingFor应该为每个对角元素返回一个列表元素.

Edit: Regarding my use case, the list elements in listElems are square and symmetric matrices. If the block is a diagonal matrix, theFunctionImLookingFor should return a list element for each diagonal element.

但是,该函数应该能够处理诸如以下的构造块矩阵

However, the function should be able to deal with building block matrices like

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

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

即在不是对角矩阵的块中处理零.

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

推荐答案

我希望这对您的所有情况都适用,底部的测试包括一个包含零的块.

I hope this will work for all your cases, the test at the bottom includes a block that contains zeroes.

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

这篇关于R:是否有一种简单有效的方法来获取块对角矩阵的构建块矩阵列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆