Comparing two matriced
Show older comments
Hi,
Is there a fast way to compare the differences between two matrices with the same dimension:
example Assume A and B each is a 1000x1000 matrix. Is there a way to find where A and B differ in one step?
Answers (4)
Jan
on 10 Mar 2011
And if the matrices are results of floating point computation a certian relative or absolute tolerance might be helpful:
abs_d = (A - B) < Tol
rel_d = ((A - B) ./ min(A, B)) < Tol
And now the same tools as replied by Walter, Sean and Matt can be applied.
Sean de Wolski
on 10 Mar 2011
The logical matric
ABne = A~=B
or if you need the indices
[r c] = find(ABne);
Matt Fig
on 10 Mar 2011
And a visual method:
spy(A~=B)
And a quick method to count the number of locations where A is not equal to B:
nnz(A~=B)
8 Comments
Sean de Wolski
on 10 Mar 2011
Matt, I get NNZ taking significantly longer than sum(:):
A = rand(1000)>.5;
B = rand(1000)>.5;
idx = A~=B;
t1 = 0;
t2 = 0;
for ii = 1:10
tic
S1 = sum(idx(:));
t1 = t1+toc;
tic
S2 = nnz(idx);
t2 = t2+toc;
end
isequal(S1,S2)
t1/t2
ans =
1
ans =
0.13468
Jan
on 10 Mar 2011
@Sean: There have been several discussion in CSSM about SUM versus NNZ. The winner changed with the Matlab versions. To my surprise SUM(SUM(idx)) is 45% faster than SUM(idx(:)) even on my single core processor in Matlab 2009a.
Sean de Wolski
on 10 Mar 2011
Interesting Jan. I have sum(sum()) is about equal on my MAC laptop running 2009b 64bit.
Matt Fig
on 10 Mar 2011
@Sean, yes, NNZ is slower than SUM - I don't recommend using it in a loop.
Who has a guess as to what NNZ is doing with its time under the hood?
Sean de Wolski
on 10 Mar 2011
It was last updated (according to my 2009b) in 2006. Could that have something to do with its sluggishness?
Matt Fig
on 10 Mar 2011
I don't think that is it. I bet TMW knew how to program a simple FOR loop in C back in 2006. I could be wrong of course :).
Jan
on 10 Mar 2011
NNZ is *much* faster in SSE, especially if the data are aligned at 128 bit boundaries.
Sean de Wolski
on 10 Mar 2011
I find it funny how the help for nnz says:
The density of a sparse matrix S is nnz(S)/prod(size(S))"
But M-Lint now says:
numel(S) is faster than prod(size(S))"
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!