通过循环创建块矩阵

时间:2014-03-07 11:33:33

标签: r matrix

我正在尝试使用R中的循环创建一个块矩阵,这取决于我调用T的一些变量。用于构造块矩阵的两个矩阵可能如下所示:

A=matrix(c(1,0.3,0.3,1.5),nrow=2)

B=matrix(c(0.5,0.3,0.3,1.5),nrow=2)

因此,根据我设置的T,我需要不同的结果。对于T = 2:

C=rbind(cbind(A,B),cbind(B,A))

对于T = 3:

C=rbind(cbind(A,B,B),cbind(B,A,B),cbind(B,B,A))

对于T = 5:

C=rbind(cbind(A,B,B,B,B),cbind(B,A,B,B,B),cbind(B,B,A,B,B),cbind(B,B,B,A,B),cbind(B,B,B,B,A))

所以基本上,我只是想创建一个循环或类似的东西,我可以指定我的T,它将根据T为我创建块矩阵。

由于

3 个答案:

答案 0 :(得分:1)

你可以这样做:

N <- nrow(A)
C <- matrix(NA,N*T,N*T)
for (i in 1:T){
   for (j in 1:T){
     if (i == j)
        C[(i-1)*N+1:N, (j-1)*N+1:N] <- A
     else
        C[(i-1)*N+1:N, (j-1)*N+1:N] <- B
   }
}

答案 1 :(得分:0)

根据你的解释,我想你最终矩阵中需要单个A和T-1 Bs。

如果这是正确的,那么可以使用combinat库中的permn函数进行快速尝试。我所做的只是使用置换生成表达式,然后对其进行评估。

A = matrix(c(1,0.3,0.3,1.5),nrow=2)
B = matrix(c(0.5,0.3,0.3,1.5),nrow=2)
T = 5
x = c("A", rep("B",T-1))
perms = unique(permn(x)) #permn generates non-unique permutations
perms = lapply(perms, function(xx) {xx=paste(xx,collapse=","); xx=paste("cbind(",xx,")")})
perms = paste(perms, collapse=",")
perms = paste("C = rbind(",perms,")",collapse=",")
eval(parse(text=perms))

答案 2 :(得分:0)

使用blockmatrix包这非常简单。

library(blockmatrix)

# create toy matrices (block matrix elements)
# with values which makes it easier to track them in the block matrix in the example here
A <- matrix("a", nrow = 2, ncol = 2)
B <- matrix("b", nrow = 2, ncol = 2)

# function for creating the block matrix
# n: number of repeating blocks in each dimension
# (I use n instead of T, to avoid confusion with T as in TRUE)
# m_list: the two matrices in a list

block <- function(n, m_list){      
  # create a 'layout matrix' of the block matrix elements
  m <- matrix("B", nrow = n, ncol = n)
  diag(m) <- "A"

  # build block matrix
  as.matrix(blockmatrix(dim = dim(m_list[[1]]), value = m, list = m_list))
}

# try with different n
block(n = 2, m_list = list(A = A, B = B))
block(n = 3, m_list = list(A = A, B = B))
block(n = 5, m_list = list(A = A, B = B))
相关问题