2017-01-29 186 views
0

我中的R大的正方形矩阵:- [R计算大NOR矩阵

norMat <- matrix(NA, nrow=1024, ncol=1024) 

这个空矩阵需要填充了所有矩阵索引对所有等于比特的总和。

所以我需要计算的逻辑NOR为i(rowIndex位置)和j(colIndex)和求和的结果,例如:

sum(intToBits(2)==intToBits(3)) 

Currenty,我有这个功能,其填埋所述矩阵:

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分钟以上,所以我很怀疑。

回答

1

我认为这是*apply函数的绝好机会。这是一个比5分钟快一点的解决方案。

首先,概念验证,非方形仅用于维度的清晰度。

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 

在技术上不需要预先计算mtximtxj。虽然intToBits没有引入太多开销,但我认为每次重新计算都很愚蠢。

我的系统是合理的(i7 6600U CPU @ 2.60GHz),win10_64,R-3.3.2 ...没什么太花哨。

+0

Thx,真是巨大的加速! – juxeii