gpt4 book ai didi

R:是否有一种简单有效的方法来取回 block 对角矩阵的构建 block 矩阵列表?

转载 作者:行者123 更新时间:2023-12-01 12:39:02 25 4
gpt4 key购买 nike

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

#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 产生构建 block :

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

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

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

但是,该函数应该能够处理像这样的构建 block 矩阵

       [,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

即处理不是对角矩阵的 block 中的零。

最佳答案

我希望这对您的所有情况都有效,底部的测试包括一个包含零的 block 。

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

关于R:是否有一种简单有效的方法来取回 block 对角矩阵的构建 block 矩阵列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26773290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com