I want to use find
function in matlab to find the index of first value that is bigger than a number C
. the list is too long and it takes a lot of time to execute. But the values are actually sorted in increasing manner. How can I take advantage of that feature of data in matlab?
Asked
Active
Viewed 158 times
1

CoderInNetwork
- 2,923
- 4
- 22
- 39
-
1[A fast implementation of find to search for intervals can be found in this answer](http://stackoverflow.com/a/20167257/2732801), you may adapt it to your needs. – Daniel Jan 29 '16 at 13:05
-
1Just realized you don't need to adapt the code. You can directly call `[a,a]=myFind(x,[C,C])` which will return you the position of the first and last number C. You may improve the performance by roughly a factor of 2 skipping the search for the last element, but I expect that it's not worth the coding effort. – Daniel Jan 29 '16 at 13:15
-
Thanks Daniel, it works great. – CoderInNetwork Jan 29 '16 at 13:20
1 Answers
2
find(Data>C,1,'first')
set the 'first'
switch in find
. This will ensure that as soon as it finds the first element satisfying the criterion it will stop looking.

Adriaan
- 17,741
- 7
- 42
- 75
-
Thanks Adriaan, Is there any solution that actually get use the sorted nature of data? some sort of embedded binary search,etc. – CoderInNetwork Jan 29 '16 at 13:05
-
This uses the fact that it's sorted, as it stops as soon as the first match is found. – Adriaan Jan 29 '16 at 13:05
-
1@Adriaan: `find` does not know / assume that the vector is sorted, thus it searches through every element until the number is found, potentially touching every element. Binary search (see answer I linked) can be much faster. – Daniel Jan 29 '16 at 13:07