FindInInterval - Find values that fall in a given interval. The equivalent Matlab code is trivial i = find(values(:,1)>=interval(1)&values(:,1)<=interval(2)); indices = [i(1),i(end)]; but becomes extremely slow when dealing with very large lists. This function can dramatically speed up things whenever one needs to repeatedly find values in a long list of intervals. USAGE indices = FindInInterval(values,interval,from) values values to test, sorted in ascending order interval [start,stop] pair from optional initial index (see example below) OUTPUT indices indices of the first and last values that fall in the interval EXAMPLE This code assumes that the variable 'interval' contains a list of non-overlapping intervals sorted in ascending order, i.e. interval(i+1,1) >= interval(i,2). previous = 1; for i = 1:n, % Find values within this window j = FindInInterval(values,interval(i,:),previous); previous = j(1); % ... do whatever computations here ... end SEE See also ConsolidateIntervals, SubtractIntervals, ExcludeIntervals, InIntervals, Restrict, CountInIntervals, PlotIntervals.
0001 %FindInInterval - Find values that fall in a given interval. 0002 % 0003 % The equivalent Matlab code is trivial 0004 % 0005 % i = find(values(:,1)>=interval(1)&values(:,1)<=interval(2)); 0006 % indices = [i(1),i(end)]; 0007 % 0008 % but becomes extremely slow when dealing with very large lists. 0009 % This function can dramatically speed up things whenever one needs 0010 % to repeatedly find values in a long list of intervals. 0011 % 0012 % USAGE 0013 % 0014 % indices = FindInInterval(values,interval,from) 0015 % 0016 % values values to test, sorted in ascending order 0017 % interval [start,stop] pair 0018 % from optional initial index (see example below) 0019 % 0020 % OUTPUT 0021 % 0022 % indices indices of the first and last values that fall 0023 % in the interval 0024 % 0025 % EXAMPLE 0026 % 0027 % This code assumes that the variable 'interval' contains a list 0028 % of non-overlapping intervals sorted in ascending order, 0029 % i.e. interval(i+1,1) >= interval(i,2). 0030 % 0031 % previous = 1; 0032 % for i = 1:n, 0033 % % Find values within this window 0034 % j = FindInInterval(values,interval(i,:),previous); 0035 % previous = j(1); 0036 % % ... do whatever computations here ... 0037 % end 0038 % 0039 % SEE 0040 % 0041 % See also ConsolidateIntervals, SubtractIntervals, ExcludeIntervals, 0042 % InIntervals, Restrict, CountInIntervals, PlotIntervals. 0043 0044 % Copyright (C) 2004-2015 by Michaƫl Zugaro 0045 % 0046 % This program is free software; you can redistribute it and/or modify 0047 % it under the terms of the GNU General Public License as published by 0048 % the Free Software Foundation; either version 3 of the License, or 0049 % (at your option) any later version.