2011-11-30 147 views
4

我有W這是一個400萬行二進制稀疏矩陣。我正在使用Matrix包。 我想能夠計算如下:基於另一個矩陣(矩陣包)的稀疏矩陣的清零元素

W2 = W %*% W    #W2 becomes a dgCMatrix 
[email protected][ [email protected] > 1 ] = 1 
W2 = W2 - W 
[email protected][ [email protected] < 0 ] = 0 

不幸的是在這次行動中的第三行完全象垃圾一樣清除我的電腦。我能夠很好地計算行(1)和(2),但是當我嘗試計算行(3)時,R需要比我有更多的RAM。我確信W2 - W比單獨的W2「更稀疏」。

是否有矢量形式的任何算法,允許在W中爲0的位置爲W2?有沒有任何有效的方法來在R中實現這一點?

+0

我修改了一下,以幫助別人避免我有的同樣的解釋錯誤。第二和第四行是微不足道的。第三條線是關鍵之一。如果映射到單變量座標列表,解決此問題並不難。 – Iterator

回答

0

我假設一個4,000,000x400,000矩陣,否則第1行將返回錯誤'A和B內部尺寸必須匹配'。

我很難複製你的問題。見下文。

> library(Matrix) 
> W<-rsparsematrix(nrow=4000000,ncol=4000000,density = .0000001) 
> W<-W>0 
> str(W) 
Formal class 'lgCMatrix' [package "Matrix"] with 6 slots 
    [email protected] i  : int [1:1600000] 623428 717198 3216269 3398149 3888958 3970651 3106201 61257 370389 3031066 ... 
    [email protected] p  : int [1:4000001] 0 2 3 3 4 5 6 6 6 7 ... 
    [email protected] Dim  : int [1:2] 4000000 4000000 
    [email protected] Dimnames:List of 2 
    .. ..$ : NULL 
    .. ..$ : NULL 
    [email protected] x  : logi [1:1600000] TRUE FALSE TRUE TRUE FALSE TRUE ... 
    [email protected] factors : list() 
> W2 <- W %*% W 
> str(W2) 
Formal class 'dgCMatrix' [package "Matrix"] with 6 slots 
    [email protected] i  : int [1:638322] 908991 1031349 2979756 1924552 3421130 992757 1375889 2872056 3161609 3389210 ... 
    [email protected] p  : int [1:4000001] 0 0 0 0 0 0 0 0 0 0 ... 
    [email protected] Dim  : int [1:2] 4000000 4000000 
    [email protected] Dimnames:List of 2 
    .. ..$ : NULL 
    .. ..$ : NULL 
    [email protected] x  : num [1:638322] 1 0 0 0 0 1 1 1 1 0 ... 
    [email protected] factors : list()  
> [email protected][ [email protected] > 1 ] = 1 
> W2 = W2 - W 
> [email protected][ [email protected] < 0 ] = 0 
> str(W2) 
Formal class 'dgCMatrix' [package "Matrix"] with 6 slots 
    [email protected] i  : int [1:2238320] 623428 717198 3216269 3398149 3888958 3970651 3106201 61257 370389 908991 ... 
    [email protected] p  : int [1:4000001] 0 2 3 3 4 5 6 6 6 7 ... 
    [email protected] Dim  : int [1:2] 4000000 4000000 
    [email protected] Dimnames:List of 2 
    .. ..$ : NULL 
    .. ..$ : NULL 
    [email protected] x  : num [1:2238320] 0 0 0 0 0 0 0 0 0 1 ... 
    [email protected] factors : list() 

重要的是,你的第2行在我的例子中什麼都不做,因爲W%*%W只返回1和0。