代码之家  ›  专栏  ›  技术社区  ›  Carrol

在矩阵中添加0作为系数

  •  1
  • Carrol  · 技术社区  · 8 年前

    我有矩阵 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  =  ?? 
    

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

    问题:

    我需要做一个加零的函数( 零 )到矩阵的行 一 .

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

    1. 它是可行的,但它太“冗长”,我相信有一种更优雅的方式来实现它——即减少代码行。
    2. 当前函数只考虑每个方程具有不同变量的情况(如上例所示)。如果我的第二个方程有变量 x2 和 X3 ,它仍将添加 零 而不是“跳过”该值。

    我的功能是:

    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 回复  |  直到 8 年前
        1
  •  1
  •   Roland    8 年前

    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
    
        2
  •  1
  •   jogo    8 年前

    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
    
    推荐文章