Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB: comparing all elements in three arrays

Tags:

arrays

matlab

I have three 1-d arrays where elements are some values and I want to compare every element in one array to all elements in other two.

For example:

a=[2,4,6,8,12]
b=[1,3,5,9,10]
c=[3,5,8,11,15]

I want to know if there are same values in different arrays (in this case there are 3,5,8)

like image 568
sasha Avatar asked Dec 08 '22 04:12

sasha


2 Answers

The answer given by AB is correct, but it is specific for the case when you have 3 arrays that you are comparing. There is another alternative that will easily scale to any number of arrays of arbitrary size. The only assumption is that each individual array contains unique (i.e. non-repeated) values:

>> allValues = sort([a(:); b(:); c(:)]);  %# Collect all of the arrays
>> repeatedValues = allValues(diff(allValues) == 0)  %# Find repeated values

repeatedValues =

     3
     5
     8

If the arrays contains repeated values, you will need to call UNIQUE on each of them before using the above solution.

like image 61
gnovice Avatar answered Dec 27 '22 08:12

gnovice


Leo is almost right, should be

unique([intersect(a,[b,c]), intersect(b,c)])
like image 36
AVB Avatar answered Dec 27 '22 08:12

AVB