Faster version of find for sorted vectors (MATLAB)

前端 未结 5 1162
心在旅途
心在旅途 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:47

    This is not an answer - I am just comparing the running time of the three solutions suggested by chappjc and Daniel R.

    N = 5e7;    % length of vector
    p = 0.99;    % probability
    KK = 100;    % number of instances
    rntm1 = zeros(KK, 1);    % runtime with ismember
    rntm2 = zeros(KK, 1);    % runtime with ismembc
    rntm3 = zeros(KK, 1);    % runtime with Daniel's function
    for kk = 1:KK
        x = cumsum(rand(N, 1) > p);
        searchfor = x(ceil(4*N/5));
    
        tic
        [tf,loc]=ismember(x, searchfor);
        inds1 = find(tf);
        rntm1(kk) = toc;
    
        tic
        tf = ismembc(x, searchfor);
        inds2 = find(tf);
        rntm2(kk) = toc;
    
        tic
        a=1;
        b=numel(x);
        c=1;
        d=numel(x);
        while (a+1

    Daniel's binary search is very fast.

    % Mean of running time
    mean([rntm1 rntm2 rntm3])
    % 0.631132275892504   0.295233981447746   0.000400786666188
    
    % Percentiles of running time
    prctile([rntm1 rntm2 rntm3], [0 25 50 75 100])
    % 0.410663611685559   0.175298784336465   0.000012828868032
    % 0.429120717937665   0.185935198821797   0.000014539383770
    % 0.582281366154709   0.268931132925888   0.000019243302048
    % 0.775917520641649   0.385297304740352   0.000026940622867
    % 1.063753914942895   0.592429428396956   0.037773746662356
    

提交回复
热议问题