在矩阵中添加 0 作为系数

Adding 0 as coefficients in matrixes

我有矩阵 A 和我的系数,矩阵 x 有受影响的变量的索引。

A <- matrix(c(1,2,-1,2),2,2)
x <- rbind(c(1,2), c(3,4))

每一行(同时在两个矩阵上)写一个等式。对于我的示例,这将是(?? 表明矩阵 b 不影响我的问题):

  x1 - 1*x2  =  ?? 
2*x3 + 2*x4  =  ?? 

这意味着 x3x4 在第一个方程 (0*x3 + 0*x4) 中有 0 作为系数。这也发生在其他变量的第二个等式上。

问题:

我需要创建一个函数,将零 (0) 添加到矩阵的行中 A

到目前为止我做了一个简单的函数,但它也有很多问题:

  1. 它有效,但它太过 "wordy",而且我确信有更优雅的方法来做到这一点 - 即更少的代码行。
  2. 当前函数只考虑每个方程有不同变量的情况(如上例所示)。如果我的第二个等式有变​​量 x2x3,它仍然会添加一个 0,而不是 "skipping" 该值。

我的函数是:

prepareCoeffs <- function(A, x) {
  # Create new coefficients matrixes
  newA <- matrix(nrow = 0, ncol = nrow(x) * ncol(x))

  # Iterate through A
  for(i in 1:nrow(A)) {
    # Prepare row
    newRow <- c()

    # Iterate through x
    for(j in 1:nrow(x)) {
        if(i == j) {
            newRow <- c(newRow, A[i,])
        } else {
            newRow <- c(newRow, rep(0, ncol(x)))
        }
    }

    newA <- rbind(newA, newRow)
  }

  # Return the new matrix
  return(newA)
}

可以在以下位置测试工作示例:http://rextester.com/BHZKL16068

我相信这应该可以满足您的需要。它使用稀疏矩阵。

A <- matrix(c(1,2,-1,2),2,2)
x <- rbind(c(1,2), c(3,4))

library(reshape)
x <- melt(x)

library(Matrix)
A <- sparseMatrix(i = x$X1, j = x$value, x = c(A))
#2 x 4 sparse Matrix of class "dgCMatrix"
#
#[1,] 1 -1 . .
#[2,] .  . 2 2


#example of using the matrix   
A %*% (1:4)
#2 x 1 Matrix of class "dgeMatrix"
#     [,1]
#[1,]   -1
#[2,]   14

这是一个解决方案,基数 R:

A <- matrix(c(1,2,-1,2),2,2)
x <- rbind(c(1,2), c(3,4))

M <- matrix(0, nrow(A), max(x))
for (i in 1:nrow(A)) M[i, x[i,]] <- A[i,]
M
# > M
#      [,1] [,2] [,3] [,4]
# [1,]    1   -1    0    0
# [2,]    0    0    2    2