我有两个矩阵,一个是二进制(零或一个),另一个是相同维度的整数矩阵,这些是方矩阵。
我想要一种以特定方式组合它们的有效方法,而不需要沿着每个元素进行迭代。
我想要将它们组合起来的方法是从矩阵A和矩阵B得到一个结果矩阵,对于该元素,得到的最小数字不是零。
任何人都可以想到R中的一个技巧来实现这一点,我已经尝试以数学的方式做到这一点,但是我一直想知道是否有办法用条件语句覆盖矩阵?
答案 0 :(得分:2)
我的猜测是:
ifelse(A == 0, B, pmin(A, B))
或者
ifelse(A == 0, B, ifelse(B == 0, A, pmin(A, B)))
如果这不是您要找的,请澄清(并提供一个示例。)
答案 1 :(得分:2)
matA <- matrix(-8:7, 4,4); set.seed(123)
matB <- matrix(sample(0:1, 16, repl=TRUE), 4, 4)
matC <- matrix(NA, nrow(matA), ncol(matA))
matC[] <- pmin( matA, MatB)
matC[ matB==0] <- matA[matB==0]
matB
#-----------
[,1] [,2] [,3] [,4]
[1,] 0 1 1 1
[2,] 1 0 0 1
[3,] 0 1 1 0
[4,] 1 1 0 1
matC
#---------
[,1] [,2] [,3] [,4]
[1,] -8 -4 0 1
[2,] -7 -3 1 1
[3,] -6 -2 1 6
[4,] -5 -1 3 1
flodel的方法产生:
> ifelse(matB == 0, matB, pmin(matA, matB))
[,1] [,2] [,3] [,4]
[1,] 0 -4 0 1
[2,] -7 0 0 1
[3,] 0 -2 1 0
[4,] -5 -1 0 1
mnel的方法产生:
> (matB * !matA) + matA
[,1] [,2] [,3] [,4]
[1,] -8 -4 1 4
[2,] -7 -3 1 5
[3,] -6 -2 2 6
[4,] -5 -1 3 7
答案 2 :(得分:1)
从@ A_Skeleton关于缩放的评论中,你可以将矩阵分解为块:
mnel <- function(matA, matB) {
(matB * !matA) + matA
}
# method takes a function as the argument
mcombine <- function(matA, matB, method) {
chunkSize <- 10000
matC <- matrix(0, nrow(matA), ncol(matA))
for (i in 1:floor(nrow(matA) / chunkSize)) {
curRange <- (chunkSize * (i-1) + 1):(i * chunkSize)
matC[curRange,] <- method(matA[curRange,], matB[curRange,])
}
# handle case where dimensions don't divide exactly into chunks
lastRange <- i*chunkSize:nrow(matA)
matC[lastRange,] <- method(matA[lastRange,], matB[lastRange,])
matC
}
# Using mnel's method:
matC <- mcombine(matA, matB, mnel)