Search code examples
arraysmatlabcomplement

How to get an array "complement" of another?


the easiest way for me to explain what i want is with an example:

a = 1:20

b = [2,7,12,18]

Now I want c to be [1,3,4,5,6,8,...,19,20] with length 16: length(a) - length(b) of course.

Is there a way for me to get c?


Solution

  • What you want is called set difference in most languages. In MATLAB, you can use the setdiff function:

    a=1:20;
    >> b=[2,7,12,18];
    >> setdiff(a,b);
    
    ans =
    
    Columns 1 through 11
    
     1     3     4     5     6     8     9    10    11    13    14
    
    Columns 12 through 16
    
    15    16    17    19    20