How to test that range values are contained in any of another range values in MATLAB?

Viewed 209

I am trying to check if in two vectors having multiple entries containing pair of ranges, whether a range from one vector is part of another range?

I have one test range vector, which contain pair of entries such as: tr=[99 143]; The entries may be more than one pair also. I'm trying to check whether this range is sub-range of any of the paired entries from another vector, such as v=[9 79 97 190 205 278 293 304];

Im using MATLAB platfrom. The answer from above example should be 97-190.

2 Answers

Here's a vectorized way using logical comparisons with implicit expansion, find and accumarray.

Let's consider a more general example, where some ranges in tr do not appear in v, or appear more than once:

tr = [99 143 10 20 40 99];
v = [9 79 97 190 205 278 293 304 99 143];

Then

c = (tr(1:2:end) >= v(1:2:end).') & (tr(2:2:end) <= v(2:2:end).'); % subrange conditions
[ii, jj] = find(c); % row and column indices of true entries
result = accumarray(jj, ii, [numel(tr)/2 1], @(t){v([2*t-1 2*t])}); % build result

gives

>> celldisp(result)
result{1} =
    97   190
    99   143
result{2} =
     9    79
result{3} =
     []

indicating that the first range in tr (99 143) is contained in two ranges in v (97 190 and 99 143), the second in one, the third in none.

This is the code, which i tried. This is giving correct results on this test set.

 tr=[99 143];
 v=[9 79 97 190 205 278 293 304];
 for i=1:2:length(tr)
     for j=1:2:length(v)
      if(tr(i)>=v(j) && tr(i+1) <=v(j+1))    
        display('yes');
        tr(i) 
        tr(i+1)
        v(j)
        v(j+1)
       end 
     end
 end

Looking forward to more efficient answer than this.

Related