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

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현