MATLAB: A way to short-circuit “any”

anylogical?optimization

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

Best Answer

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.