Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: vectorized version of searchsorted

Tags:

julia

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.

like image 579
user3055163 Avatar asked Oct 27 '25 10:10

user3055163


2 Answers

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.

like image 127
carstenbauer Avatar answered Oct 29 '25 08:10

carstenbauer


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)

like image 43
Bogumił Kamiński Avatar answered Oct 29 '25 08:10

Bogumił Kamiński