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

1 次查看(过去 30 天)
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 个评论
Bruno Luong
Bruno Luong 2018-10-9
编辑:Bruno Luong 2018-10-9
function calls: that implies some small mxArray header copying, etc... we talking about sub µs by calling here.
Jan
Jan 2018-10-9
编辑:Jan 2018-10-9
@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.

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by