Search code examples
matlabdifferencecell-array

Remove all rows in cell array A that are in cell array B


I have a cell array A in MATLAB as follow

A = { 'U2', 'T13', 'A52';  
      'U2', 'T15', 'A52';  
      'U2', 'T18', 'A52';  
      'U2', 'T17', 'A995'; 
      'U4', 'T18', 'A53';  
      'U4', 'T13', 'A64';  
      'U4', 'T18', 'A64';
    }

I also have a cell array B as follow:

B = { 'U2', 'T13', 'A52';  
      'U2', 'T18', 'A52';   
      'U4', 'T13', 'A64';  
      'U4', 'T18', 'A64';
     }

How to generate cell array C is equal to A - B:

C = { 'U2', 'T15', 'A52';  
      'U2', 'T17', 'A995'; 
      'U4', 'T18', 'A53';  
    }

How to get C?


Solution

  • This one-liner should serve your purposes:

    C = A(sum(~ismember(A,B),2) > 0,:)
    

    The output is:

    C =
        3×3 cell array
        'U2'    'T15'    'A52' 
        'U2'    'T17'    'A995'
        'U4'    'T18'    'A53'
    

    Basically, the row elements of A that are not found in B show a row-wise summation value greater than 0. That reference value is then used to produce a logical indexing that catches the element not present in B.

    There is a nice overload of the ismember function that accepts rows as third input argument in order to perform row-wise matchings. This would really simplify this computation, but unfortunately it is not supported for cell array inputs.

    EDIT

    A = {
      'U2' 'T13' 'A52';  
      'U2' 'T15' 'A52';  
      'U2' 'T18' 'A52';  
      'U2' 'T17' 'A995'; 
      'U4' 'T18' 'A53';  
      'U4' 'T13' 'A64';  
      'U4' 'T18' 'A64'
    };
    
    B = {
      'U2' 'T13' 'A52';  
      'U2' 'T18' 'A52';   
      'U4' 'T13' 'A64';  
      'U4' 'T18' 'A64'
    };
    
    A_len = size(A,1);
    A_keys = cell(A_len,1);
    
    for i = 1:A_len
        A_keys{i} = horzcat(A{i,:});
    end
    
    B_len = size(B,1);
    B_keys = cell(B_len,1);
    
    for i = 1:B_len
        B_keys{i} = horzcat(B{i,:});
    end
    
    C = A(~ismember(A_keys,B_keys),:);