Selecting close matches from one array based on another reference array

前端 未结 3 1450
萌比男神i
萌比男神i 2020-12-02 01:33

I have an array A and a reference array B. Size of A is at least as big as B. e.g.

A = [2,100,300,793,130         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 01:46

    You can use MATLAB interp1 function that exactly does what you want.
    option nearest is used to find nearest points and there is no need to specify a threshold.

    out = interp1(A, A, B, 'nearest', 'extrap');
    

    comparing with other method:

    A = sort(randi([0,1000000],1,10000));
    
    B = sort(randi([0,1000000],1,4000));
    
    disp('---interp1----------------')
    tic
        out = interp1(A, A, B, 'nearest', 'extrap');
    toc
    disp('---subtraction with threshold------')
    %numpy version is the same
    tic
        [dists, ind] = min(abs(bsxfun(@minus, A, B.')), [], 2);
    toc
    

    Result:

    ---interp1----------------
    Elapsed time is 0.00778699 seconds.
    ---subtraction with threshold------
    Elapsed time is 0.445485 seconds.
    

    interp1 can be used for inputs larger than 10000 and 4000 but in subtrction method out of memory error occured.

提交回复
热议问题