Faster version of find for sorted vectors (MATLAB)

前端 未结 5 1168
心在旅途
心在旅途 2020-11-27 17:51

I have code of the following kind in MATLAB:

indices = find([1 2 2 3 3 3 4 5 6 7 7] == 3)

This returns 4,5,6 - the indices of elements in t

5条回答
  •  悲&欢浪女
    2020-11-27 18:24

    Here is a fast implementation using binary search. This file is also available on github

    function [b,c]=findInSorted(x,range)
    %findInSorted fast binary search replacement for ismember(A,B) for the
    %special case where the first input argument is sorted.
    %   
    %   [a,b] = findInSorted(x,s) returns the range which is equal to s. 
    %   r=a:b and r=find(x == s) produce the same result   
    %  
    %   [a,b] = findInSorted(x,[from,to]) returns the range which is between from and to
    %   r=a:b and r=find(x >= from & x <= to) return the same result
    %
    %   For any sorted list x you can replace
    %   [lia] = ismember(x,from:to)
    %   with
    %   [a,b] = findInSorted(x,[from,to])
    %   lia=a:b
    %
    %   Examples:
    %
    %       x  = 1:99
    %       s  = 42
    %       r1 = find(x == s)
    %       [a,b] = myFind(x,s)
    %       r2 = a:b
    %       %r1 and r2 are equal
    %
    %   See also FIND, ISMEMBER.
    %
    % Author Daniel Roeske 
    
    A=range(1);
    B=range(end);
    a=1;
    b=numel(x);
    c=1;
    d=numel(x);
    if A<=x(1)
       b=a;
    end
    if B>=x(end)
        c=d;
    end
    while (a+1

提交回复
热议问题