根据我的上一个问题Add negative elements in matrix to whole row under the condition that all elements except diagonal are greater 0 导致失败,当负值大到将它们分配到行时,我找到了以下算法,我试图实现。
我开始尝试实施但直到现在才找到解决方案。 这是迄今为止的代码:
p <- matrix(c(-0.3,0.2,0.2,-0.1, 0.1,-0.4,0.4,-0.1, 0.2,-0.1,-0.4,0.3, -0.1,0.2,0.1,-0.2), ncol = 4, byrow = TRUE)
ind1 <- row(p) != col(p)
ind2 <- row(p) != col(p) & p < 0
ind.diag <- row(p) == col(p)
maxMat <- apply(p, c(1,2), FUN = function(x){max(x, 0)})
Gi <- NA
Bi <- NA
Bi <- apply(p, 1, FUN = function(x){sum(max( -p[ind1], 0))})
for (i in 1:nrow(p)){
Gi[i] <- abs(p[i, i]) + sum(maxMat[i, ])
}
GiBi <- cbind(Gi, Bi)
p.result <- p
p.result[ind2] <- 0