When to use find over logical indexing

I need to return the first value in an array that is larger than another specific value. I have:

find(A > val, 1, 'first') 

According to this post: https://stackoverflow.com/a/3908268/118328/index.php But what about:

 B = A(A > val); B(1) 

Is there any good reason to use one over the other here except for an extra line?

+6
source share
1 answer

Yes there is; speed! Especially for large arrays, find will be significantly faster.

Think about it: the operation A > val is the same in both cases, but

 B = A(A > val) 

extracts values ​​from A and copies them to a new array B , which must be assigned and assigned for copying, and the temporary element A(A> val) must be destroyed.

All find(A>val, 1, 'first') searches for a list of logical elements and returns a single number when it encounters the first true value; it is much less useless copying / assignment / etc, and therefore much faster.

As a rule, when you do not use additional parameters in find , logical indexing is almost always preferable. When you need or use additional find functions, the find option is almost always preferable.

+6
source

Source: https://habr.com/ru/post/944745/


All Articles