1

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?

Teknophilia
  • 758
  • 10
  • 23

1 Answers1

0

Both solutions posted in the comments work equally well for non-time-critical computations:

sum(sign(A) ~= sign(B)) -- Divakar

If 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.70seconds.

Community
  • 1
  • 1