Julia: vectorized version of searchsortedLinking R and Julia?Initialize an Empty Array of Tuples in JuliaPython None and numpy commands in JuliaSapply (from R) equivalent for Julia?How do I change the data type of a Julia array from “Any” to “Float64”?Julia equivalent of R's paste() functionVector of matrices in Juliasorted indexes in Julia (equivalent to numpy's argsort)Calling a Julia 0.4 function from Python. How i can make it work?Why have “clamp”, “clamp.”, and “clamp!” in Julia?

Are the requirements of a Horn of Valhalla cumulative?

What verb for taking advantage fits in "I don't want to ________ on the friendship"?

What is an example of of idiomatic "typed" WolframScript?

Most elegant way to write a one-shot 'if'

Is Cyclic Ether oxidised by periodic acid

What's the safest way to inform a new user of their password on an invite-only website?

Can I travel from Germany to England alone as an unaccompanied minor?

What is "oversubscription" in Networking?

SRAM Twist Shifter Paired with Shimano Rear Derailleur

What kind of jet plane is this?

Put my student loan in parents’ second mortgage - help?

How do I organize members in a struct to waste the least space on alignment?

The warming up game

Are gliders susceptible to bird strikes?

How do I tell the reader that my character is autistic in Fantasy?

Security Patch SUPEE-11155 - Possible issues?

Is it okay to submit a paper from a master's thesis without informing the advisor?

Which is better for keeping data: primary partition or logical partition?

13th chords on guitar

Why did NASA wet the road in front of the Space Shuttle crawler?

Find the radius of the hoop.

Why would anyone even use a Portkey?

How to describe POV characters?

Just graduated with a master’s degree, but I internalised nothing



Julia: vectorized version of searchsorted


Linking R and Julia?Initialize an Empty Array of Tuples in JuliaPython None and numpy commands in JuliaSapply (from R) equivalent for Julia?How do I change the data type of a Julia array from “Any” to “Float64”?Julia equivalent of R's paste() functionVector of matrices in Juliasorted indexes in Julia (equivalent to numpy's argsort)Calling a Julia 0.4 function from Python. How i can make it work?Why have “clamp”, “clamp.”, and “clamp!” in Julia?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















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.










share|improve this question



















  • 1





    You've received two good answers. I just wanted to point out that if B is sorted and (approximately) larger than 0.1*length(A), then you will get better performance with an algorithm that performs a single simultaneous loop over A and B. The single loop over both ends up having less operations than length(B) binary chops, which is what broadcasting over searchsortedfirst will do.

    – Colin T Bowers
    Mar 25 at 23:26


















2















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.










share|improve this question



















  • 1





    You've received two good answers. I just wanted to point out that if B is sorted and (approximately) larger than 0.1*length(A), then you will get better performance with an algorithm that performs a single simultaneous loop over A and B. The single loop over both ends up having less operations than length(B) binary chops, which is what broadcasting over searchsortedfirst will do.

    – Colin T Bowers
    Mar 25 at 23:26














2












2








2








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.










share|improve this question
















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.







julia






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 25 at 14:45







user3055163

















asked Mar 25 at 14:15









user3055163user3055163

1468 bronze badges




1468 bronze badges







  • 1





    You've received two good answers. I just wanted to point out that if B is sorted and (approximately) larger than 0.1*length(A), then you will get better performance with an algorithm that performs a single simultaneous loop over A and B. The single loop over both ends up having less operations than length(B) binary chops, which is what broadcasting over searchsortedfirst will do.

    – Colin T Bowers
    Mar 25 at 23:26













  • 1





    You've received two good answers. I just wanted to point out that if B is sorted and (approximately) larger than 0.1*length(A), then you will get better performance with an algorithm that performs a single simultaneous loop over A and B. The single loop over both ends up having less operations than length(B) binary chops, which is what broadcasting over searchsortedfirst will do.

    – Colin T Bowers
    Mar 25 at 23:26








1




1





You've received two good answers. I just wanted to point out that if B is sorted and (approximately) larger than 0.1*length(A), then you will get better performance with an algorithm that performs a single simultaneous loop over A and B. The single loop over both ends up having less operations than length(B) binary chops, which is what broadcasting over searchsortedfirst will do.

– Colin T Bowers
Mar 25 at 23:26






You've received two good answers. I just wanted to point out that if B is sorted and (approximately) larger than 0.1*length(A), then you will get better performance with an algorithm that performs a single simultaneous loop over A and B. The single loop over both ends up having less operations than length(B) binary chops, which is what broadcasting over searchsortedfirst will do.

– Colin T Bowers
Mar 25 at 23:26













2 Answers
2






active

oldest

votes


















2














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 ArrayInt64,1:
10
9
9


Compare to np.searchsorted:



julia> using PyCall

julia> np = pyimport("numpy");

julia> np.searchsorted(A,B)
3-element ArrayInt64,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.






share|improve this answer























  • Spot on. Thank you very much.

    – user3055163
    Mar 25 at 14:30











  • This is a correct equivalent of numpy code, but please note (I was writing the answer in parallel) that the numpy code does not find what you want. In particular searchsortedfirst can return you out-of-bounds index.

    – Bogumił Kamiński
    Mar 25 at 14:32











  • Haven't you interchanged A and B here? At least according to the explanation in the question?

    – DNF
    Mar 25 at 14:44











  • My question was misleading. I've corrected it.

    – user3055163
    Mar 25 at 14:46


















1














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)






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55339848%2fjulia-vectorized-version-of-searchsorted%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    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 ArrayInt64,1:
    10
    9
    9


    Compare to np.searchsorted:



    julia> using PyCall

    julia> np = pyimport("numpy");

    julia> np.searchsorted(A,B)
    3-element ArrayInt64,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.






    share|improve this answer























    • Spot on. Thank you very much.

      – user3055163
      Mar 25 at 14:30











    • This is a correct equivalent of numpy code, but please note (I was writing the answer in parallel) that the numpy code does not find what you want. In particular searchsortedfirst can return you out-of-bounds index.

      – Bogumił Kamiński
      Mar 25 at 14:32











    • Haven't you interchanged A and B here? At least according to the explanation in the question?

      – DNF
      Mar 25 at 14:44











    • My question was misleading. I've corrected it.

      – user3055163
      Mar 25 at 14:46















    2














    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 ArrayInt64,1:
    10
    9
    9


    Compare to np.searchsorted:



    julia> using PyCall

    julia> np = pyimport("numpy");

    julia> np.searchsorted(A,B)
    3-element ArrayInt64,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.






    share|improve this answer























    • Spot on. Thank you very much.

      – user3055163
      Mar 25 at 14:30











    • This is a correct equivalent of numpy code, but please note (I was writing the answer in parallel) that the numpy code does not find what you want. In particular searchsortedfirst can return you out-of-bounds index.

      – Bogumił Kamiński
      Mar 25 at 14:32











    • Haven't you interchanged A and B here? At least according to the explanation in the question?

      – DNF
      Mar 25 at 14:44











    • My question was misleading. I've corrected it.

      – user3055163
      Mar 25 at 14:46













    2












    2








    2







    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 ArrayInt64,1:
    10
    9
    9


    Compare to np.searchsorted:



    julia> using PyCall

    julia> np = pyimport("numpy");

    julia> np.searchsorted(A,B)
    3-element ArrayInt64,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.






    share|improve this answer













    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 ArrayInt64,1:
    10
    9
    9


    Compare to np.searchsorted:



    julia> using PyCall

    julia> np = pyimport("numpy");

    julia> np.searchsorted(A,B)
    3-element ArrayInt64,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.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 25 at 14:28









    crstnbrcrstnbr

    4,7381 gold badge12 silver badges25 bronze badges




    4,7381 gold badge12 silver badges25 bronze badges












    • Spot on. Thank you very much.

      – user3055163
      Mar 25 at 14:30











    • This is a correct equivalent of numpy code, but please note (I was writing the answer in parallel) that the numpy code does not find what you want. In particular searchsortedfirst can return you out-of-bounds index.

      – Bogumił Kamiński
      Mar 25 at 14:32











    • Haven't you interchanged A and B here? At least according to the explanation in the question?

      – DNF
      Mar 25 at 14:44











    • My question was misleading. I've corrected it.

      – user3055163
      Mar 25 at 14:46

















    • Spot on. Thank you very much.

      – user3055163
      Mar 25 at 14:30











    • This is a correct equivalent of numpy code, but please note (I was writing the answer in parallel) that the numpy code does not find what you want. In particular searchsortedfirst can return you out-of-bounds index.

      – Bogumił Kamiński
      Mar 25 at 14:32











    • Haven't you interchanged A and B here? At least according to the explanation in the question?

      – DNF
      Mar 25 at 14:44











    • My question was misleading. I've corrected it.

      – user3055163
      Mar 25 at 14:46
















    Spot on. Thank you very much.

    – user3055163
    Mar 25 at 14:30





    Spot on. Thank you very much.

    – user3055163
    Mar 25 at 14:30













    This is a correct equivalent of numpy code, but please note (I was writing the answer in parallel) that the numpy code does not find what you want. In particular searchsortedfirst can return you out-of-bounds index.

    – Bogumił Kamiński
    Mar 25 at 14:32





    This is a correct equivalent of numpy code, but please note (I was writing the answer in parallel) that the numpy code does not find what you want. In particular searchsortedfirst can return you out-of-bounds index.

    – Bogumił Kamiński
    Mar 25 at 14:32













    Haven't you interchanged A and B here? At least according to the explanation in the question?

    – DNF
    Mar 25 at 14:44





    Haven't you interchanged A and B here? At least according to the explanation in the question?

    – DNF
    Mar 25 at 14:44













    My question was misleading. I've corrected it.

    – user3055163
    Mar 25 at 14:46





    My question was misleading. I've corrected it.

    – user3055163
    Mar 25 at 14:46













    1














    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)






    share|improve this answer



























      1














      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)






      share|improve this answer

























        1












        1








        1







        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)






        share|improve this answer













        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)







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 25 at 14:31









        Bogumił KamińskiBogumił Kamiński

        17.9k2 gold badges18 silver badges26 bronze badges




        17.9k2 gold badges18 silver badges26 bronze badges



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid …


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55339848%2fjulia-vectorized-version-of-searchsorted%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

            Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?