Sparse matrix equality in MATLAB accidentally dense

Alec Jacobson

March 28, 2013

weblog/

I had in my code:
all(A(:) == B(:))
where A and B where both large, sparse matrices. Unfortunately the == operator in MATLAB is not conducted in a sparse way. Try this:

n=20000;
tic;
A = sparse(n,n);
B= sparse(n,n);
all(A(:)==B(:));
toc
There are zero non-zeros so this should cost no time at all. But the all() function is of course not smart enough to unravel the == operator. So this is the same as doing:
C = A(:) == B(:);
And of course all the zeros that match will turn into 1s in C, so if A and B are the same C will be completely dense. Instead I should use the built-in
isequal(A,B);
Note that in the case where is A mostly the same as B then
~any(A(:)~=B(:))
will be fast. But if they're different, this is effectively dense as above.