R 计算大 NOR 矩阵
R Calculate big NOR matrix
我在 R 中有一个很大的方阵:
norMat <- matrix(NA, nrow=1024, ncol=1024)
这个空矩阵需要用所有矩阵索引对的所有相等位的总和来填充。
所以我需要计算 i
(rowIndex) 和 j
(colIndex) 的逻辑 NOR 并对结果求和,例如:
sum(intToBits(2)==intToBits(3))
目前,我有这个填充矩阵的函数:
norMatrix <- function()
{
matDim=1024
norMat <<- matrix(NA, nrow=matDim, ncol=matDim)
for(i in 0:(matDim-1)) {
for(j in 0:(matDim-1)) {
norMat[i+1,j+1] = norsum(i,j)
}
}
return(norMat)
}
这里是 norsum
函数:
norsum <- function(bucket1, bucket2)
{
res = sum(intToBits(bucket1)==intToBits(bucket2))
return(res)
}
这是填充矩阵的有效解决方案吗?
我不确定,因为在我的机器上这需要超过 5 分钟。
我认为这是 *apply
功能的绝佳机会。这是一个比 5 分钟快一点的解决方案。
首先,概念验证,non-square 仅用于清晰度。
nc <- 5
nr <- 6
mtxi <- sapply(seq_len(nc), intToBits)
mtxj <- sapply(seq_len(nr), intToBits)
sapply(1:nc, function(i) sapply(1:nr, function(j) sum(mtxi[,i] == mtxj[,j])))
# [,1] [,2] [,3] [,4] [,5]
# [1,] 32 30 31 30 31
# [2,] 30 32 31 30 29
# [3,] 31 31 32 29 30
# [4,] 30 30 29 32 31
# [5,] 31 29 30 31 32
# [6,] 29 31 30 31 30
假设这些都是正确的,全餐交易:
n <- 1024
mtx <- sapply(seq_len(n), intToBits)
system.time(
ret <- sapply(1:n, function(i) sapply(1:n, function(j) sum(mtx[,i] == mtx[,j])))
)
# user system elapsed
# 3.25 0.00 3.36
从技术上讲,您不需要 pre-calculate mtxi
和 mtxj
。虽然 intToBits
不会引入太多开销,但我认为每次都重新计算是愚蠢的。
我的系统是合理的 (i7 6600U CPU @ 2.60GHz),win10_64,R-3.3.2 ...没什么特别的。
我在 R 中有一个很大的方阵:
norMat <- matrix(NA, nrow=1024, ncol=1024)
这个空矩阵需要用所有矩阵索引对的所有相等位的总和来填充。
所以我需要计算 i
(rowIndex) 和 j
(colIndex) 的逻辑 NOR 并对结果求和,例如:
sum(intToBits(2)==intToBits(3))
目前,我有这个填充矩阵的函数:
norMatrix <- function()
{
matDim=1024
norMat <<- matrix(NA, nrow=matDim, ncol=matDim)
for(i in 0:(matDim-1)) {
for(j in 0:(matDim-1)) {
norMat[i+1,j+1] = norsum(i,j)
}
}
return(norMat)
}
这里是 norsum
函数:
norsum <- function(bucket1, bucket2)
{
res = sum(intToBits(bucket1)==intToBits(bucket2))
return(res)
}
这是填充矩阵的有效解决方案吗? 我不确定,因为在我的机器上这需要超过 5 分钟。
我认为这是 *apply
功能的绝佳机会。这是一个比 5 分钟快一点的解决方案。
首先,概念验证,non-square 仅用于清晰度。
nc <- 5
nr <- 6
mtxi <- sapply(seq_len(nc), intToBits)
mtxj <- sapply(seq_len(nr), intToBits)
sapply(1:nc, function(i) sapply(1:nr, function(j) sum(mtxi[,i] == mtxj[,j])))
# [,1] [,2] [,3] [,4] [,5]
# [1,] 32 30 31 30 31
# [2,] 30 32 31 30 29
# [3,] 31 31 32 29 30
# [4,] 30 30 29 32 31
# [5,] 31 29 30 31 32
# [6,] 29 31 30 31 30
假设这些都是正确的,全餐交易:
n <- 1024
mtx <- sapply(seq_len(n), intToBits)
system.time(
ret <- sapply(1:n, function(i) sapply(1:n, function(j) sum(mtx[,i] == mtx[,j])))
)
# user system elapsed
# 3.25 0.00 3.36
从技术上讲,您不需要 pre-calculate mtxi
和 mtxj
。虽然 intToBits
不会引入太多开销,但我认为每次都重新计算是愚蠢的。
我的系统是合理的 (i7 6600U CPU @ 2.60GHz),win10_64,R-3.3.2 ...没什么特别的。