Clayton Stanley
Clayton Stanley

Reputation: 7784

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

Which looks like this in non-sparse form:

>> 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

>> 

EDIT:

I would like to do a matrix multiplication of these sparse vectors, and return a sparse array:

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

NRowSums * NColSums (I think; or if that returns a scalar, then flip them) w/o using a non-sparse variable to temporarily store data.

EDIT2:

I currently have this:

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

This seems a bit awkward for what I'm trying to do, especially the type castings. It's also extremely inneficient, because it computes all elements where either a NRowSum or NColSum exist, and not only the intersection of these two. That is, there are about 100x more entries in this NSums than in the original sparse matrix.

Upvotes: 2

Views: 749

Answers (3)

Housen
Housen

Reputation: 106

Check the package "pracma" http://cran.r-project.org/web/packages/pracma/index.html Then you can use bsxfun() just as in Matlab.

Upvotes: 3

IRTFM
IRTFM

Reputation: 263362

If you really do have a "sparse" situation, I think you probably want to start with

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.

At the moment your example is not suitable for testing since it is dense.

Upvotes: 1

Yanshuai Cao
Yanshuai Cao

Reputation: 1297

You can transpose your B array to be the same layout as A first:

B = t(B)

then call the outer product of the two arrays:

outer(A,B)

Upvotes: 0

Related Questions