For each value in array B, how to find the closest value in array A with one function call, similar to how searchsorted(A, B) works in numpy.
searchsortedfirst.(Ref(A),B)
should give you the desired result. Example:
julia> A = [1, 2, 2, 4, 4, 4, 4, 4, 9, 10];
julia> B = [10, 6, 9];
julia> searchsortedfirst.(Ref(A), B)
3-element Array{Int64,1}:
10
9
9
Compare to np.searchsorted:
julia> using PyCall
julia> np = pyimport("numpy");
julia> np.searchsorted(A,B)
3-element Array{Int64,1}:
9
8
8
which (up to Python's 0-based indexing) is equivalent.
Explanation:
What does searchsortedfirst.(Ref(A),B) do?
The dot tells Julia to broadcast the searchsortedfirst call. However, we have to make sure that A is still treated as an array in each call (we want A to be a scalar under broadcasting). This can be achieved by wrapping A in a Ref.
Assuming B is unsorted (but then you cannot use searchsorted in numpy either) you can do:
[argmin(abs(a .- B)) for a in A]
If B is sorted and you accept that you do not find the closest value in array B (searchsorted does not find the closest value) you can write:
searchsorted.(Ref(B), A)
and you will get ranges in which elements of A sould be placed in B (you can also checkout functions searchsortedfirst and searchsortedlast)
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