MATLAB Answers


Union and Interseciton of Intervals

Asked by Joris Lambrecht on 9 Jun 2011

I want to be able to quickly determine the interval resulting from unions and intersections of various intervals. The number of intervals may vary, so the method needs to be somewhat flexible.

In regular Matlab I have only found a way to intersect sets (e.g. {1,2,3} u {2,4}) not intervals (e.g. [0.1 3.3) n (1.1 2.9])

where 'u' indicates union and 'n' indicates intersection.

Example: ([1.1, 2.3] u [2.8 3.2]) n ([1.9, 3.1] u [4.2 4.3]) n [1.7, 3.2] = [1.9,2.3] u [2.8, 3.1]

In MuPad, you can do the following: (Dom::Interval([1.1, 2.3]) union Dom::Interval(2.8, 3.2)) intersect (Dom::Interval([1.9, 3.1]) union Dom::Interval(4.2, 4.3)) intersect (Dom::Interval([1.7, 3.2]))

Any ideas on how to do this without MuPad? I've seen the 'interval merging' file exchange entry but it only handles unions of intervals.




No products are associated with this question.

2 Answers

Answer by Sean de Wolski
on 9 Jun 2011
doc intersect
doc union

and friends. Beware of floating points, however.

fpno = @(x)uint32(x*1000); %get rid of floating points
fpyes = @(x)double(x)/1000;  %bring 'em back
fpyes(intersect(fpno([1.1 2.2]), fpno(1.2:.1:3.4)))

But I still don't understand how you're defining the interval as I can't get the same results as your example.


intersect and union functions only operate on sets (not intervals). Like you say, beware floating points:
intersect([1.1 2.2], [1.2 3.4])
ans =

Empty matrix: 1-by-0
I want the result [1.2 2.2]

I can multiply my floating point numbers by a factor (determining precision, e.g. 1000 will result in 3 decimal place precsion), round them to make integers, construct sets from the integers, operate on these sets (using intersect and union), and then divide by my factor to get back to floating point. However this seems unnecessary and will generate large arrays to compare if I want high precision.

So what increment are you using to define an "interval"?

Answer by Walter Roberson
on 9 Jun 2011

Union and intersection of intervals can be done with min() and max() and appropriate logic; I remember implementing the logic about 6 years ago (probably in perl.) I did not, however, have to worry about open vs closed intervals: the representation and logic gets messier for those.


Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!