0

I have Two Arrays in MATLAB, Say A and B contains random values as below. Both arrays A and B always contain a pair; 2,4,6 or 8 or more elements (even number only) and A always has less elements than B. And elements in both arrays are pre-sorted.

A=[152 271];
B=[107 266 314 517 538 732];

I want to check the range of values of all pairs (one pair, 152-271 in this example) in A against all pairs of B. And expand/modify the values of pairs of B as such, if it exceed the B values. In this example, first to compare pair 152-271 of A with first pair of B (i.e. 107-266). As 152 is greater than 107, and 271 is greater than 266. We will modify 266 values of first pair of B with 271 to wholly include the range of first pair of A within B. Both intervals (range) in A and B should somewhat overlap to modify the B values.We will stop when there are no elements to check in A. The end result will be like this:

A=[152 271];
B=[107 271 314 517 538 732];

In this image below Green,Rad and Yellow represent A,B and final B (only modified) values respectively. enter image description here

erbal
  • 421
  • 5
  • 18
  • Are you considering sliding pairs from A and B or are those disjoint pairs? – Divakar Sep 27 '15 at 10:37
  • Also when you compare `152 271` with B's `314 517`, shouldn't it change `314` to `152`, if I got it right? – Divakar Sep 27 '15 at 10:48
  • Both intervals (range) in A and B should somewhat overlap to modify. – erbal Sep 27 '15 at 11:22
  • Somewhat similar to this question: [SE](http://stackoverflow.com/questions/15593066/overlapping-time-intervals-without-for-while-loops), but disjoiint pairs. – erbal Sep 27 '15 at 13:01
  • Found answer at [MATLAB Newsgroup](http://www.mathworks.com/matlabcentral/newsreader/view_thread/171594) by Roger Stafford. – erbal Sep 27 '15 at 17:38

2 Answers2

0

You can use find with the option last to identify the indices in B

A=[152 271 280 320];
B=[107 266 314 517 538 732];

for interval = 1:numel(A)-1
    %get the index of the lower interval bound in B
    index=find(B<=A(interval),1,'last');
    %increase the upper interval bound if nessecary
    B(index+1)=max(B(index+1),A(interval+1));
end

As you did not specify any corner cases (Intervals in A exceeds B) I did not conciser them. If they can happen, you need to extend the code.

Daniel
  • 36,610
  • 3
  • 36
  • 69
0
A=[152 271];
B=[107 266 314 517 538 732];    
mat=[A B];
A1 = vec2mat(mat,2)
n = size(mat,1);
[t,p] = sort(mat(:));
z = cumsum(accumarray((1:2*n)',2*(p<=n)-1));
z1 = [0;z(1:end-1)];
A2 = [t(z1==0 & z>0),t(z1>0 & z==0)]
% Reference Link: (http://www.mathworks.com/matlabcentral/newsreader/view_thread/171594) by Roger Stafford
erbal
  • 421
  • 5
  • 18