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?
logical indexing is usually faster than find - MATLAB Answers - MATLAB Central.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With