Search code examples
matlabsparse-matrixbsxfun

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.


Solution

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