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.
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With