簡體   English   中英

如何將此“稀疏”的Matlab bsxfun調用轉換為R?

[英]How do I translate this 'sparse' Matlab bsxfun call to R?

>> A = sparse([1,2,3,4,5])

A =

   (1,1)        1
   (1,2)        2
   (1,3)        3
   (1,4)        4
   (1,5)        5

>> B = sparse([1;2;3;4;5])

B =

   (1,1)        1
   (2,1)        2
   (3,1)        3
   (4,1)        4
   (5,1)        5

>> bsxfun(@times, A, B)

ans =

   (1,1)        1
   (2,1)        2
   (3,1)        3
   (4,1)        4
   (5,1)        5
   (1,2)        2
   (2,2)        4
   (3,2)        6
   (4,2)        8
   (5,2)       10
   (1,3)        3
   (2,3)        6
   (3,3)        9
   (4,3)       12
   (5,3)       15
   (1,4)        4
   (2,4)        8
   (3,4)       12
   (4,4)       16
   (5,4)       20
   (1,5)        5
   (2,5)       10
   (3,5)       15
   (4,5)       20
   (5,5)       25

非稀疏形式如下所示:

>> full(ans)

ans =

     1     2     3     4     5
     2     4     6     8    10
     3     6     9    12    15
     4     8    12    16    20
     5    10    15    20    25

>> 

編輯:

我想對這些稀疏向量進行矩陣乘法,並返回一個稀疏數組:

> class(NRowSums)
[1] "dsparseVector"
attr(,"package")
[1] "Matrix"
> class(NColSums)
[1] "dsparseVector"
attr(,"package")
[1] "Matrix"
> 

NRowSums * NColSums(我認為;或者,如果返回標量,則將其翻轉)w / o使用非稀疏變量臨時存儲數據。

EDIT2:

我目前有這個:

NSums = tcrossprod(as(NRowSums, "sparseMatrix"), as(NColSums, "sparseMatrix"))

對於我想做的事情,尤其是類型轉換,這似乎有些尷尬。 這也是極其無效的,因為它會計算NRowSum或NColSum存在的所有元素,而不僅計算這兩個元素的交集。 也就是說,此NSum中的條目大約比原始稀疏矩陣中的條目多100倍。

檢查包“ pracma” http://cran.r-project.org/web/packages/pracma/index.html然后,您可以像在Matlab中一樣使用bsxfun()。

如果您確實有“稀疏”情況,我想您可能想從

df <- expand.grid(A=A, B=B)
df$val <- with(df, A*B))
# then pass that triple column set of i,j, and values to the sparse matrix constructors.

目前,您的示例比較密集,因此不適合進行測試。

您可以先將B數組轉置為與A相同的布局:

B = t(B)

然后調用兩個數組的外部乘積:

outer(A,B)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM