Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is bsxfun usable with sparse matrices

I want to a element-by-element binary operation apply to large logical vectors. The content of these vectors is manly false, so for performance considerations it better to work with sparse matrices. If i do so the resulting matrix is not correct.

Examble

A = logical([0;1;0;0]);
B = logical([0 0 1 1]);

C = bsxfun(@and,A,B)

In this case C is

 C = 
     0     0     0     0
     0     0     1     1
     0     0     0     0
     0     0     0     0

If i use sparse matrices C is

 C = full(bsxfun(@and,sparse(A),sparse(B)))
 C = 
     0     0     0     0
     1     1     1     1
     0     0     0     0
     0     0     0     0

Which is obviously wrong.

Did i oversee something or is this a Matlab bug.

like image 537
Tobias Heß Avatar asked Dec 08 '11 10:12

Tobias Heß


People also ask

When would you use a sparse matrix?

Using sparse matrices to store data that contains a large number of zero-valued elements can both save a significant amount of memory and speed up the processing of that data. sparse is an attribute that you can assign to any two-dimensional MATLAB® matrix that is composed of double or logical elements.

Do sparse matrices use less memory?

Sparse matrices are necessary for dealing with large single-cell RNA-seq datasets. They require less memory than dense matrices, and they allow some computations to be more efficient. In this note, we'll discuss the internals of the dgCMatrix class with examples.


1 Answers

I can reproduce this so it certainly seems to be a MATLAB bug. Especially considering that:

C = full(bsxfun(@times,sparse(A),sparse(B)))

C =

     0     0     0     0
     0     0     1     1
     0     0     0     0
     0     0     0     0

So, I would report it to The Mathworks.

However, in this particular case, I can't help feeling that bsxfun with sparse matrices isn't going to be the most efficient. Consider the following:

A = sparse(logical([0;1;0;0]));
B = sparse(logical([0 0 1 1]));

C_bsxfun = bsxfun(@and,full(A),full(B));

[i j] = ndgrid(find(A), find(B));
C_sparse = sparse(i, j, true, numel(A), numel(B));

isequal(C_bsxfun, full(C_sparse))
like image 73
Nzbuu Avatar answered Oct 23 '22 10:10

Nzbuu