Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use find over logical indexing

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

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

According to this post: https://stackoverflow.com/a/9464886/1985603 find is unavoidable in this case. But, what about:

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

Is there a good reason to use one over the other here, other than the extra line?

like image 710
mlai Avatar asked May 10 '13 22:05

mlai


People also ask

What is faster than find in MATLAB?

logical indexing is usually faster than find - MATLAB Answers - MATLAB Central.

What does logical indexing mean?

In logical indexing, you use a single, logical array for the matrix subscript. MATLAB extracts the matrix elements corresponding to the nonzero values of the logical array. The output is always in the form of a column vector. For example, A(A > 12) extracts all the elements of A that are greater than 12.

What happens when a vector is indexed by a vector of logicals Booleans?

A logical vector is a vector that only contains TRUE and FALSE values. In R, true values are designated with TRUE, and false values with FALSE. When you index a vector with a logical vector, R will return values of the vector for which the indexing vector is TRUE.


1 Answers

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 into a new array B, which will have to be allocated and copy-assigned, and the A(A> val) temporary will have to be destroyed.

All find(A>val, 1, 'first') does is walk the list of logicals, and return a single number when it encounters the first true value; this is a lot less useless copying/assigning/etc., and therefore, much faster.

As a rule of thumb, when you don't use the additional options in find, logical indexing is almost always preferable. When you need or use find's additional functionalities, the find option is almost always preferable.

like image 184
Rody Oldenhuis Avatar answered Oct 22 '22 21:10

Rody Oldenhuis