Using find() is faster than direct logical indexing?
13 views (last 30 days)
Does it make sense that using find() instead of direct logical indexing is faster in this example:
Jan on 3 Aug 2022
No relevant difference in R2022a in the forum:
A=randi(100, 5e3, 5e3); % Few elements only
But as soon as the number of occurences grows, the timings differ:
A = randi(2, 5e3, 5e3); % More occurences: about 50%
function B = useFind(A)
I = find(A == 2);
B = A;
B(I) = 3;
function B = useLogical(A)
B = A;
B(A == 2) = 3;
My interpretation: find has a certain overhead and providing a vector as index is more expensive, because each element must be checked if it is inside the valid range with an integer value. The logical index must be checked only once.
For a tiny index vector, the find method has an advantage, because the logical indexing must process a lot of false elements. This seems to be implemented inefficiently in Matlab, see FEX: CopyMask, which ist much faster (up to 66%!) than Y = X(Mask) with logical indexing. It uses a simple method to avoid branching:
*Y = X[i];
Y += Mask[i];
If the index vector is larger, e.g. 50% of the data, the find() method is less efficient than logical indexing.