Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the elements in an array that is not in another array

Tags:

matlab

I have two arrays lets say A = [1;2;4;7;10;20]; B = [1;4;8];

Now I want to find the elements of A, that are not in B i.e; [2;7;10;20]. I just need their index that is the index of the elements [2;7;10;20] in A. How can I implement this in matlab. I can use loops and all. But that is not what I want. I want an elegant solution. Suggestions?

like image 955
user34790 Avatar asked Nov 22 '12 15:11

user34790


2 Answers

You can do that using the ismember function.

A = [1;2;4;7;10;20]; 
B = [1;4;8];
ismem = ismember(A,B);

will give you

[1 0 1 0 0 0]'

If you really need the indices, you can use find.

find(ismem==0)

Just as a reminder, you can always use logical indexing like so:

A(~ismem)

will give you

[2 7 10 20]'
like image 200
HebeleHododo Avatar answered Sep 17 '22 18:09

HebeleHododo


If you want the elements of A which are not in B you can use setdiff.

If you want the indices of the elements rather than their values, you can use ismember and negate the result.

like image 28
jam Avatar answered Sep 19 '22 18:09

jam