A way to short-circuit "any"?

2 views (last 30 days)
Kyle
Kyle on 24 Jul 2012
Hello,
My code is bottlenecked by many calls of the following line:
if any(vectorA & vectorB)
where vectorA and vectorB are large, sparse, and logical.
Specifically, these vectors are 1.4M elements long and average 0.6% non-zeros. However, due to the previous calculations, they share a common non-zero quite often (say roughly half the time). As written, the & operation is performed before the any.
Since this is the natural bottleneck, I've been looking for ways to improve the computation, and short circuiting out comes to mind, but I haven't found an elegant way to do this in Matlab.
Does anyone know a slick optimization?
Thanks!
-Kyle

Accepted Answer

Jan
Jan on 24 Jul 2012
Edited: Jan on 24 Jul 2012
Is the multiplication faster?
if any(vectorA .* vectorB)
But I do not assume that this helps, because you still process more elements than needed. You need a Mex function for short-cutting. For full arrays you find in the FEX: anyExceed and anyEq. But substantial modifications are required for accessing sparse arrays.
  1 Comment
Kyle
Kyle on 24 Jul 2012
Thanks for the reply!
I should have mentioned this up front- I tried .* but didn't find it to be substantially faster.
I'll look into the file exchange functions- thanks for the tip. Trying to use full vector routines is disastrously slow, but I'll see if I can make modifications.

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 24 Jul 2012
In previous discussions, it has been a bit of a mystery about whether any() short-circuits or not. If I recall correctly, timing tests (Jan's, probably) indicated that some short-circuiting was going on but not in strictly linear ways. If I recall, there is a FEX contribution that short-circuits logic operations.
However, the above was with respect to full arrays, not sparse.
  2 Comments
Jan
Jan on 24 Jul 2012
any([1, zeros(1, 1000)]) is faster than any([zeros(1, 1000), 1]). But Kyle wants to shortcut the & actually, if any value triggers the any already.
Walter Roberson
Walter Roberson on 24 Jul 2012
I wonder... wasn't there something discussed a couple of months ago, about how "if" (and perhaps "while") now short-circuit & and | in some cases, but that other contexts use the full evaluation? Just maybe
if ~(A & B)
would short-circuit even for sparse.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements 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!