find(condition,1) is slower than using a loop--any way to speed up?

1 view (last 30 days)
In general, using a logical condition in conjunction with find is slower than using a tight loop:
loc = find(X>a, 1)
is slower than using a for loop:
for i = 1:N
if(X(i)>a)
loc = i;
break;
end
end
The reason for this is because the logical operator X>a operates on all elements of the vector X, which is wasteful. Surely the JIT is smart enough to optimize
find(condition,1)
such that condition is applied and tested until the value is found. Do any shortcuts for this optimization exist?
  33 Comments
Bruno Luong
Bruno Luong on 9 Oct 2018
Edited: Bruno Luong on 9 Oct 2018
function calls: that implies some small mxArray header copying, etc... we talking about sub µs by calling here.
Jan
Jan on 9 Oct 2018
Edited: Jan on 9 Oct 2018
@Bruno: In the worst case, all X and compared in the Mex function and in find(X>a, 1). That the latter is faster might be caused by MMX/SSE code, which checks 8 or 16 logicals at once. SSE could be used for the comparison also, but the code will be much larger and has to catch the exceptions that the mxArray does not start or end at a multiple of the cache-line size. If we take into account the runtime and teh programming+debug time of the code, your simple C-Mex function is likely to be optimal. Please post is as an answer, because it solves the problem.

Sign in to comment.

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!