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

1 vue (au cours des 30 derniers jours)
Marshall
Marshall le 5 Oct 2018
Modifié(e) : Jan le 9 Oct 2018
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 commentaires
Bruno Luong
Bruno Luong le 9 Oct 2018
Modifié(e) : Bruno Luong le 9 Oct 2018
function calls: that implies some small mxArray header copying, etc... we talking about sub µs by calling here.
Jan
Jan le 9 Oct 2018
Modifié(e) : Jan le 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.

Connectez-vous pour commenter.

Réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by