A way to short-circuit "any"?
2 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
More Answers (1)
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
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
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.
See Also
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!