No License

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video

Highlights from

Join the 15-year community celebration.

Play games and win prizes!

» Learn more

5.0 | 1 rating Rate this file 4 Downloads (last 30 days) File Size: 1.56 KB File ID: #19359 Version: 1.0




28 Mar 2008 (Updated )

Finds the intersection (common elements) of several (more than two) arrays

| Watch this File

File Information

In MATLAB, there is a command called "intersect", which finds the set intersection (common elements) of two vectors. However, this command doesn't work if I want to compare more than two vectors and find out their intersection. Therefore, I decided to write this function which is called "intersect2". It can find the common elements of any number of 1D numeric arrays of the same or different sizes and returns an array consisting of only those elements.

The input variable "cell" has to be a cell array, with each cell occupied by an 1D numeric array. For example, if you want to find the intersection (common elements) of the following three arrays
       a = [ 1 3 4 6 8 9 ];
       b = [ 3 1 0 8 6 4 ];
       c = [ 7 8 1 9 3 4 ];,
you need to first put all of them into a cell array, i.e.
       cell = {a, b, c};
Then you could use "cell" as the input variable to this function, i.e.
       result = intersect2(cell);
The output of this function is simply an array consisting of elements that are common to all the arrays stored in "cell". For the particular case in the example above, the output would be
       result = [ 1 3 4 8 ];
Also note that the numbers in the result are sorted in ascending order.

MATLAB release MATLAB 7.4 (R2007a)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (3)
27 Mar 2012 Ulrik

Ulrik (view profile)

but I would change the code a bit:

n = numel(cell);
if n == 2
result = intersect(cell{1}, cell{2});
elseif (n > 2 && rem(n,2) == 0)
for i = 1:(n/2)
intersections{1, i} = intersect(cell{i}, cell{n-i+1});
elseif (n > 2 && rem(n,2) == 1)
for i = 1:((n-1)/2)
intersections{1, i} = intersect(cell{i}, cell{n-i+1});
intersections{1, i+1} = cell{(n+1)/2};
error('You need at least two arrays as inputs');

if n > 2
result = intersect2(intersections);

24 Jul 2009 Julia

Julia (view profile)

I've submitted a script that fulfills the same function as this one, using a recursive scheme:
intersect several arrays

There is a similar one for the union of several arrays:

Comment only
08 May 2008 Thierry Dalon

I would code this using recursivity:
function res=intersectall(c)

if length(c) == 2
res = intersect(c{1}, c{2});

res = intersect(c{1},intersectall(c(2:end)));

Comment only

Contact us