I have two vectors (actually 1xN matrices) that have numbers between [-1, 1]. I want to find the number of instances where the sign of two corresponding elements is not the same (sign(A[k]) ~= sign(B[k])). Is there a way to do this that's more efficient than just iterating over the two vectors?
Asked
Active
Viewed 38 times
1
-
3`sum(sign(A) ~= sign(B))`? – Divakar Feb 19 '15 at 22:15
-
4If you're feeling playful: `nnz(A.*B<0)` – Luis Mendo Feb 19 '15 at 22:17
-
@LuisMendo - One more for the hell of it. This is rather obfuscated: `A = (A + 1)/2; B = (B + 1) / 2; C = accumarray([A(:)+1 B(:)+1], 1); out = C(2) + C(3);` Nowhere near as efficient as your's and Divakar's, but just another way of completely blowing up this comments stream. – rayryeng Feb 19 '15 at 22:23
-
@rayryeng With `accumarray`! Hahaha, it would have never occured to me :-) – Luis Mendo Feb 19 '15 at 22:26
-
1@LuisMendo - hehehe I know. Basically what I'm doing is I'm tallying up combinations of `[-1,1], [1,-1], [-1,-1]` and `[1,1]` between `A` and `B` then summing up the occurrences of `[-1,1]` and `[1,-1]` together. – rayryeng Feb 19 '15 at 22:28
-
2@rayryeng when you have a big hammer, everything looks like a nail! – David Feb 19 '15 at 22:43
-
@David - ahahaha that's really funny. That was my laugh of the day. Thank you :) – rayryeng Feb 19 '15 at 22:46
-
@David: More like: sledgehammer! – knedlsepp Feb 20 '15 at 00:03
-
@Divakar, thanks I will use this approach. – Teknophilia Feb 20 '15 at 00:48
1 Answers
0
Both solutions posted in the comments work equally well for non-time-critical computations:
sum(sign(A) ~= sign(B))
-- DivakarIf you're feeling playful:
nnz(A.*B<0)
-- Luis Mendo
But the non-playful version sum(sign(A) ~= sign(B))
appears to be faster, presumably because it avoids multiplications involved in A.*B
. I compared them like this:
Reps = 1e7;
n = 10;
tic;
for i=1:Reps
A = rand(1,n)-.5;
B = rand(1,n)-.5;
differ = sum(sign(A) ~= sign(B)); % or nnz(A.*B<0);
end
toc;
For the sum-of-signs version, computation time was 18.95
seconds; for the A.*B
version, it was 47.70
seconds.

Community
- 1
- 1