我有一个矩阵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
作为系数。在其他变量的第二个方程式上也会发生这种情况。
问题:
我需要创建一个将零(0
)添加到矩阵A
的行中的函数。
到目前为止,我做了一个简单的功能,但是它也有问题:
x2
和x3
,它将仍然添加一个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
答案 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