在矩阵中加0作为系数

时间:2018-08-02 14:06:57

标签: r for-loop equation-solving linear-equation

我有一个矩阵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)中具有0*x3 + 0*x4作为系数。在其他变量的第二个方程式上也会发生这种情况。

问题:

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

到目前为止,我做了一个简单的功能,但是它也有问题:

  1. 它可以工作,但是太“罗word”了,我敢肯定,有一种更优雅的方法可以做到-即更少的代码行。
  2. 当前函数仅考虑每个方程式具有不同变量的情况(如上例所示)。如果我的第二个方程式包含变量x2x3,它将仍然添加一个0,而不是“跳过”该值。

我的功能是:

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

以下是基于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