Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Julia, how do I get the index of the first element in a sorted array that exceeds a certain value?

Tags:

arrays

julia

Here is my code (x is the sorted array):

lookup_value = 310.0
x = [298.0, 303.0, 308.0, 313.0, 323.0]
if (issorted(x))
    idx = searchsorted(x, lookup_value)
end

In this particular case, the value of idx is:

4:3

Here, I'd like to extract either the "4" (the first element exceeding my look up value) or "3" (the last element that does not exceed the look up value). However, I'm unable to do so by converting the range to an array, as all I get from the following command is an empty array:

julia> collect(idx)
0-element Array{Int64,1}

Note that the lookup value of 310.0 is only an example; this variable could take on different values.

like image 303
nathanielng Avatar asked Apr 20 '16 09:04

nathanielng


Video Answer


1 Answers

I just realised its possible to use idx.start and idx.stop to access the start and end of a range.

julia> idx
4:3
julia> idx.start
4
julia> idx.stop
3

The first element that exceeds the lookup value is x[idx.start]. The last element that does not exceed the lookup value is x[idx.stop].

like image 92
nathanielng Avatar answered Sep 27 '22 20:09

nathanielng